Reputation: 32321
This is my simple program (code inside the try catch block) that will be responsible to call a webservice running. Basically this is responsible to log the event of the application to a webService:
updated question code
package com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
HttpURLConnection conn = null;
NetClientPost() throws Exception {
URL url = new URL("http://localhost:8080/RestTest/custom/log_service");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
}
public static void main(String[] args) {
NetClientPost po;
try {
po = new NetClientPost();
po.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void execute() {
try {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"eee 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 281
Reputation: 19
In the JavaDoc:
"Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time. "
(http://docs.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html)
So looks like you can create each time new instance. Something like that:
...
private void getConnection() {
conn = (HttpURLConnection) url.openConnection();
}
...
Then when outputs to webservice you need to close streams but need not to call desconnect() otherwise you will stop sharing underlying network connection (which will degrade the performance of your application).
Upvotes: 1
Reputation: 35453
If the calls are only happening one time per second, and only one thread is doing this (i.e. no concurrency), then opening connection, calling and then disconnecting is fine. If you were doing hundreds of calls per second and/or had high currency/low latency requirements then reusing the connection (keep-alive) and pooling (for concurrency support) might be appropriate as the TCP handshake when connecting is time consuming. If that's the case ever, then look into Apache Http Components or Async Http Client (if you prefer NIO) as they will handle these complexities for you.
Upvotes: 0
Reputation: 310916
will it not create too many HTTPConnections as logging happens every second.
No, it won't. HttpURLConnection
does connection pooling behind the scenes. Very likely a single connection will continue to be re-used. The only way you can prevent that is by calling disconnect()
, which you should therefore avoid. However you should certainly close the input and output streams of the connection, which you aren't doing.
Upvotes: 0
Reputation: 9941
You should move it to a different method (because thats better code not because of functionality). This method is invoked by your main
. And you need to close the connection.
I assume you want to have each call registered on the server side as a new request. (Otherwise please see the answer of @Santosh). Then it is important that you open a new connection every time, thus close it every time as well.
public void doSomething() {
logMyself();
// do whatever the program does
}
private static void logMyself() {
// you can put the next line into the constructor.
URL url = new URL(
"http://192.168.2.46:8080/RestTest/custom/log_service");
HttpURLConnection conn;
try {
// you can NOT put the next line into the constructor.
conn = (HttpURLConnection) url.openConnection()
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"micromax 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
} catch //...
} finally {
// its important to put the disconnect into the finally.
conn.disconnect();
}
}
Upvotes: 1
Reputation: 17903
It appears that this code runs only once in your application. Please correct me if I am missing anything. There could be two use cases here
You are running this piece of code only once i.e. open connection, post the data and then disconnect. For this, what you have (first snippet) will suffice.
You are invoking the web services multiple times. i.e. open connection once, and use the same connection multiple times to invoke the web services. Here the second snippet (or the code which creates connection in constructor) of the code is appropirate. You call disconnect only when you are sure that there will not be any further call to that URL. Javadoc for disconnect()
says following
Indicates that other requests to the server are unlikely in the near future. Calling disconnect() should not imply that this HttpURLConnection instance can be reused for other requests.
Upvotes: 0