java.net.ConnectException: errno: 110 (Connection timed out) - java

I'm trying to connect client server, where I'm facing below mentioned error while opening connection:
java.net.ConnectException: errno: 110 (Connection timed out), error:
Connection timed out (local port XXXXX to address 0:0:0:0:0:0:0:0, remote
port XXXX to address XXX.XXX.XXX.XX)
Code Snippet:
URL url = new URL("http://XXX.XXX.XXX.XX:XXXX/services/ServiceEngine");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(json);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();

Connection timeouts happen when the server fails to respond in a pre-determined time period and shouldn't have much to do with the logic in your code.
You can change this time period with the HttpURLConnection.setConnectTimeout() like this:
connection.setConnectTimeout(10000); //Time is set in milliseconds, so 1000 is 1 second.
Also as another user pointed out it could be that your server isn't actually up and ready to host connections.

Related

How can I call HttpUrlConnection disconnect()

My code sends HttpConnection and then tries to use either connection.getInputStream() or connection.getErrorStream() to deserialize response.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // getErrorStream()
String content = in.lines().collect(Collectors.joining());
How can I pass connection to parse(HttpURLConnection connection) function and call connection.disconnect() after it's finished()?
I was thinking about
connection.disconnect();
return MyObject.fromString(connection.getInputStream(), connection.getErrorStream());
but not sure whether it makes sense to disconnect before reading the response.
You can do something like this:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String content = parse(connection);
connection.disconnect();
// do something with content

Re-Establishing connection to Proxy Server

I have an interesting scenario here. I have a proxy server address that is supposed to provide me a new exit IP every time I make an HTTP request to it. I have noticed that the exit IP will change only after I restart the program, as opposed to every loop iteration. Below is my source.
Loop calls getHTML every iteration:
String result = getHTML("https://wtfismyip.com/text");
public static String getHTML(String urlToRead) throws Exception {
InetSocketAddress addy = new InetSocketAddress("example.proxy.com", 1234);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addy);
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
conn.disconnect();
return result.toString();
}
Result will continue to be the same IP every time, until I restart the program. I feel like some stream or socket hasn't been closed yet and it keeps the connection alive.
Found the answer to my problem. The TCP socket was being kept alive, and would allow it to keep tunneling to the proxy without reconnecting.
I needed to add this statement somewhere in my code, I put it at the beginning of this class's initialization.
System.setProperty("http.keepAlive", "false");

Tomcat - Getting Java SSLException hostname in certificate didn't match

On my machine (on a main method) I am able to consume an https web service using this code:
URL url;
HttpsURLConnection connection;
HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
return true;
}
});
//prepare the request
byte[] postData = xml.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
url = new URL(ENDPOINT_URL);//https endpoint
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(postData);
//make the request and get response xml string
connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
Notice that on the code I bypass hostname verification, according to the answers to this post: Java SSLException: hostname in certificate didn't match
But if I try to consume the exact same https web service, using the exact same code, on the the exact same machine (my local machine), but from a webapp deployed on Tomcat 8, I get the error:
Caused by: javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No name matching localhost found
I have searched for anwsers and solutions to this problem but found none. I am clueless. Do you have any idea why is this happening?

IOException when trying to read http connection response

I'm submitting the request below in Java via a Websphere Portlet.
It works fine when I submit manually using postman (chrome extension) but cannot get it to succeed via java.
What am I missing?
I imported the SSL cert from remote host into Websphere, so SSL connections are not the issue.
Exception in logs ..
[7/15/14 23:06:39:993 BST] 00000170 ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service CWSRV0014E: Uncaught service() exception root cause MyApp: java.io.IOException: Server returned HTTP response code: 500 for URL: https://server.com/msg
This is the java code invoking the request and trying to read the response ..
URL url = new URL("https://server.com/msg");
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String body = URLEncoder.encode("{\"x\": \"hello\"}", "UTF-8");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(body);
out.close();
// Exception occurs here ..
BufferedReader rd2 = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = rd2.readLine()) != null) {
result += line;
}
rd2.close();
This was solution, to not URLEncoder.encode() the POST body ..
URL url = new URL(queries.getQuery(sessionBean.getSelectedQuery()));
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String json = "{\"x\": \"hello\"}";
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(json);
out.close();
BufferedReader rd2 = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = rd2.readLine()) != null) {
result += line;
}
rd2.close();

Android HttpUrlConnection Response wait time

I have below code. I am getting HTTP response code -1. Just to troubleshoot, I would like to know if I should wait after making connection for a while before checking the http response code.
String requestURL = "https://www.google.com";
HttpURLConnection connection = new HttpURLConnection;
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(this.connection.getOutputStream());
writer.write(getHttpData());
writer.flush();
writer.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new inputStreamReader(connection.getInputStream()));
}
Is getResponseCode() or getInputStream() blocking call ? Am I reading response too soon ? Should I wait ?
Thanks for the help.
One reason you could be getting the weird HTTP response code of -1 is the connection-pooling with-http-keep-alives bug that's in Android platform versions up to (and including) Froyo, ie Android v2.2.
The Android Developer Blog gives the following code snippet to resolve the problem (note that they say it doesn't include Froyo, although we found that it did - the snippet below is modified accordingly):
private void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) <= Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
Try calling that when your app starts-up and see if it fixes your problem.

Categories