How to re-use socket connections? [duplicate] - java

This question already has answers here:
Persistent HttpURLConnection in Java
(3 answers)
Closed 9 years ago.
I am interested in reusing an HttpUrlConnection (as part of a statefull protocol between server and client that I'm developing).
I know that there is an Connection=keep-alive header for persistent http.
Now, I want to know how to reuse such a conenction.
I have written this code:
URL u = new java.net.URL("http://localhost:8080/Abc/Def");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Connection", "keep-alive");
c.setHeader("A","B");
c.getInputStream() //here I see that server gets my messages (using DEBUG)
c.setHeader("B","C"); //
Now how do I resend this "B" header to the server, I tried re-connect etc,but nothing gets it to work.
And the server also perform response.setHeader("Connection", "keep-alive");
I've looked in many forums, but no one wrote about this. Maybe HttpURLConnection doesn't handle this?

You don't. You close this one and create a new one. It does TCP connection pooling and keepalive behind the scenes.

Related

HttpURLConnection, openConnection and setRequestMethod("GET"

I am currently trying to understand the logic behind each of the code below. Please let me know if I am correct and answer my confusions.
urlConnection = (HttpURLConnection) url.openConnection();
//connection object is created. However, do not understand
//"manipulate parameters that affect the connection to the remote resource."
urlConnection.setRequestMethod("GET");
//set the method for the URL request. Not sure what that means!
//there are other strings that could be used, but not sure what each means,
//and couldn't the Java documentations didn't seem to have explanations either
urlConnection.connect();
//the actual connection the the remote object is made
This question is not related to Java at all. What you need is to understand HTTP protocol and do some comprehensive reading. I recommend starting with
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
and then read:
https://www.rfc-editor.org/rfc/rfc7230

Parallelize HttpsURLConnection in Java

I am working on an application which executes a lot of HTTP-Post Request on a specific URL. The data gets included into the request via a JSON File. Performing a single POST request takes about 200ms until I get the response code back. In order to parallelize these Request I started using different Worker Threads, opening a HTTPURLConnection each and posting their requests over this connection.
Unfortunately I do not see much improvement, so I wanted to clarify the underlying situation of the TCP sockets and get some thoughts from you guys.
Each of my workers executes the request like the following example could.
public void submitRequest() {
URL url = new URL("https://example.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
DataOutputStream output = new DataOutputStream(conn.getOutputStream());
// Construct the POST data.
String content = generatedJSONString();
// Send the request data
output.writeBytes(content);
output.flush();
output.close();
// Check response code here
int response = conn.getResponseCode();
}
Because each worker uses its own HttpsURLConnection, I assume that the necessary TLS handshake is only done once per worker and the requests can then be executed without the need of an additional handshake? I want each worker to use its own TCP connection to the server. I tried to check with Wireshark, but it does not show me the TLS handshake, I don't really know why.
Even with 50 workers in parallel, my code does not execute fast enough to post the relevant data to the url. Therefore I ask myself the question if its because of the TCP connections not getting saturated by the code, because the JSON data (usually 10 key-value pairs) is to little data compared to the TCP/HTTP overhead. If not I might ask the service provider to think about a better way to deliver data in a batch way, to submit more JSON data per individual POST request. I also changed to code to use the Apache HTTPClient, but I got similar performance, therefore I think there is a mistake in the way I think the TLS connections get established and reused.

Android HttpURLConnection- easiest way to trust all hosts? [duplicate]

This question already has answers here:
Trusting all certificates using HttpClient over HTTPS
(22 answers)
Closed 8 years ago.
I'm trying to hit an https site through an Android client:
URL url = new URL(myurl);
Log.d("Connection", myurl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.addRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
Log.d("Connection", "Connecting...");
conn.connect();
The connect call is throwing an exception:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
EDIT: I'm told the site is using a self-signed certificate, and since this is only a prototype I just need to trust all hosts so it will work. Can someone point me toward a simple example of doing this? The code I've seen online gets quite complicated, I just want to do a hacky bypass of any verification.
Are you sure that the password you are supplying is correct? This answer suggests that the connection can appear to hang if the password is incorrect.
I fixed it by creating a new .csr with the right Organizational Unit Name and Common Name
Hope you are using HTTPS in your URL.

How to Reuse HttpUrlConnection? [duplicate]

This question already has answers here:
Persistent HttpURLConnection in Java
(3 answers)
Closed 9 years ago.
I am interested in reusing an HttpUrlConnection (as part of a statefull protocol between server and client that I'm developing).
I know that there is an Connection=keep-alive header for persistent http.
Now, I want to know how to reuse such a conenction.
I have written this code:
URL u = new java.net.URL("http://localhost:8080/Abc/Def");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Connection", "keep-alive");
c.setHeader("A","B");
c.getInputStream() //here I see that server gets my messages (using DEBUG)
c.setHeader("B","C"); //
Now how do I resend this "B" header to the server, I tried re-connect etc,but nothing gets it to work.
And the server also perform response.setHeader("Connection", "keep-alive");
I've looked in many forums, but no one wrote about this. Maybe HttpURLConnection doesn't handle this?
You don't. You close this one and create a new one. It does TCP connection pooling and keepalive behind the scenes.

Servlet communticating with another server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
communication between remote servlets
Is it possible to send objects between servlets on different servers?
The issue is, when my servlet receives a http request, before sending a response, it would need to send some data to another web application (on different server), get a response, and then process the received data. However I don't really know how to tackle the problem. Is it possible for a servlet to send a http request to another servlet, and then get the response from it?
Of course it is possible - you can create an HttpURLConnection in it in the same way you would do it from JavaSE. Usually what I do is, in case of an error, to forward to the client the original (second server) HTTP error code.
Here's an example of how to use HttpURLConnection to communicate with another servlet (or any http server)...
URL url = new URL ("http://host/myservlet");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput (true);
connection.setDoInput (true);
OutputStream os = connection.getOutputStream();
//TODO: optionally, send something through the OutputStream to your servlet
os.flush();
os.close();
InputStream is = connection.getInputStream();
//TODO: retrieve your results from the InputStream
is.close();
Be sure to close your streams when done or use try-with-resources blocks. You can use ObjectInputStream or InputStreamReader based on your needs. You can also use the setRequestProperty method of the HttpURLConnection to define things such as the user-agent or cookies if needed.

Categories

Resources