HttpURLConnection error: java.net.SocketTimeoutException: Connection timed out - java

I am using simple urlconnection like this:
url = URL+"getClient&uid="+cl_id;
URL url = new URL(this.url);
Log.d("Set++","get_t URL: "+ url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
its working fine, but sometimes i get this error:
error: java.net.SocketTimeoutException: Connection timed out
what could be the reason? I have only 4 clients... so i dont think that the server is overloaded with connections.
the code:
try {
URL = Settings.BASE_URL + "_interface.php?" +
"key=" + Settings.KEY +"&app_naam="+Settings.APP_NAAM+ "&action=check&setTime="+c;
URL url = new URL(URL);
if(D)Log.e("ChekTreadAanvr+url", URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String response;
if ((response = rd.readLine()) != null) {
rd.close();
}
if(D) Log.d("WebSaveThread+","DATARESIEVED: "+response);
return response;
} catch (MalformedURLException e) {
if(D)Log.d("ERR","server chekc failure ++ ");
return success = false;
} catch (IOException ioex) {
if(D)Log.e("ERR", "error: " + ioex.getMessage(), ioex);
success = false;
}
return Boolean.toString(success);

It may be possible that your Internet Connection Speed is weak. You can increase your Timeout Interval by using following method.
httpURLConnection.setConnectTimeout( 6 * 10 * 1000 ); // One Minute

If you are connecting to a particularly slow server, there are two timeouts that you can set: setConnectTimeout() and setReadTimeout(). The names are fairly self explanatory. For example:
httpURLConnection.setConnectTimeout(60*1000);
httpURLConnection.setReadTimeout(60*1000);

Related

Calling an API that have username and password in Java

I'm trying to connect to an API that has a username and password with this code:
try {
URL url = new URL("https://url?UserName=username&Password=password");
Connection = (HttpURLConnection) url.openConnection();
//Request setup
Connection.setRequestMethod("GET");
Connection.setConnectTimeout(5000);
Connection.setReadTimeout(5000);
int status = Connection.getResponseCode();
System.out.println(status);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
But I get the error:
java.net.SocketException: Connection reset
I kept searching and I found another format for the URL which is:
URL url = new URL("Https:username:password#url);
When I tried, it gave me the error:
java.net.MalformedURLException: For input string:password#url
I tried to separate the URL into three strings and made the password Integer.pharsInt("String"), but it also didn't work.
The password has words, numbers, and a special character!
What am I doing wrong?
Try to encode your URL, this way:
HttpURLConnection connection = (HttpURLConnection)
new URL("https://url?UserName" +
URLEncoder.encode(username, "UTF-8") +
"&Password=" +
URLEncoder.encode(password, "UTF-8"))
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// The rest of your code

Google Recaptcha from java failing with connection timeout

I am trying to add google recaptcha in my application. below is the code for validating google captcha.
try {
URL obj = new URL("https://www.google.com/recaptcha/api/siteverify");
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Properties properties = System.getProperties();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setConnectTimeout(30 * 1000);
con.setReadTimeout(30 * 1000);
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
if (MyConstants.IS_PROXY_ENABLED) {
properties.put("http.proxyHost",MyConstants.HTTP_PROXY_HOST);
properties.put("http.proxyPort",MyConstants.HTTP_PROXY_PORT);
String authString = MyConstants.HTTP_PROXY_AUTHENTICATION;
String encodedAuthString = "Basic "
+ new sun.misc.BASE64Encoder().encode(authString.getBytes());
con.setRequestProperty("Proxy-authorization",encodedAuthString);
}
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + SITE_VERIFY_URL);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
//parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return jsonObject.getBoolean("success");
}catch(Exception e){
e.printStackTrace();
return false;
}
It is failing with Connection Timeout error every time. I tried to set the timeout but it didn't help.
Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:271)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:328)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:778)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:881)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
When i am trying to access https://www.google.com/recaptcha/api/siteverify from browser with input params it gives me result
{
"success": true,
"challenge_ts": "2018-10-12T22:07:18Z",
"hostname": "localhost"
}
Can someone please help me why connection timeout error is coming from code?

How to fix "Connection Reset" in Eclipse for HTTPS url

I am trying to parse a https url link and getting a connection reset problem in eclipse , however it works in eclipse ( returns 301 response code though )
How to solve this ?
Thanks
try {
String url = "http://api.demo.globalgatewaye4.firstdata.com/transaction/search?start_date=2018-01-07&end_date=2018-01-09";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Authorization", "Basic *****************");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
System.out.println("Response Code ... " + status);
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
System.out.println("URL Content... \n" + html.toString());
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
This returns a HTTP response code "301" which redirects it to a HTTPS url which in turn give s a connection reset error .
How to solve this error in eclipse , or is there a generic way .
Thank you . Found the solution . problem was related to TLS not being available in the java version i was using .
Had to switch to a higher java version .

URL is not resolved in ubuntu 14.04

I have a cron job schedule in my Ubuntu or Runnable JAR running.
I have received an exception on my string URL but on my Windows development it is OK. it could not resolve the correct string url please check below
java.io.FileNotFoundException: http://www.carlolotti.com/enoteca-vini-valdostani/chardonnay-elevé-en-fut-de-chene-anselmet-2007-6s0jwecq.asp
here is the source code:
HttpURLConnection conn;
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(true);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
int responseCode = conn.getResponseCode();
if(debug)
System.out.println("\nSending 'GET' request to URL : " + url);
if(debug)
System.out.println("Response Code : " + responseCode);
try{
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream() , "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
//inputLine=StringEscapeUtils.escapeHtml3(inputLine);
//if(inputLine.contains("Albari"))
// t=1;
response.append(inputLine);
if(csv)
response.append(lineRet);
}
in.close();
return response;
}catch(Exception e){
e.printStackTrace();
}
return null;
I'm suspecting the Language of my Ubuntu on my Locale LANG=en_GB.UTF-8 Do I need to change this to en_US.UTF-8? I'm not really sure about it but this is my 1st investigation.
You have to replace the éin the url with é.

HttpURLConnection: empty header causing NullPointerException in Notes Java Agent

A couple of months ago I wrote a Java Agent that synchs documents in Notes databases with tickets in a Redmine system. The agent opens a Notes document through an HttpURLConnection and it worked perfectly until two weeks ago (no changes to the code or server were made). Now a NullPointerException is thrown when conn.getResponseCode() is called and I can't figure out why, since the URL used for the connection works fine when I copy and paste it into my browser (using the same credentials as the agent does). As you can see in the code block below I also tried printing out the header fields of the connection object, but it returns an empty map, {}.
The stack trace I get looks like the one pasted in this question and I tried all the solutions suggested there, but it didn't solve the problem. Interestingly, when I try to save the document to Redmine, the method creating a new issue there (using the Redmine Java API) also fails because it cannot establish an HTTP connection. Again: this used to work flawlessly before.
I have been trying to fix this for two days now with no success. The agent is allowed to run restricted operations with full administration rights (3) and the databases it accesses are on the same server as the DB containig the agent, and the default access in the ACL is "author". Any ideas what could be causing this issue? Thanks in advance!
String issueBody = "";
Session session = getSession();
Name serverName = session.createName(db.getServer());
URL url = null;
java.net.HttpURLConnection conn = null;
InputStream is;
BufferedReader rd;
String line;
String urlString = "http://"+serverName.getCommon()+":80/"+db.getFilePath()+"/"+VIEW_SPRS_BY_SPRNO+"/" + issue.getUniversalID() + "/Body?OpenField";
urlString = urlString.replace("\\", "/");
String userpass = httpUser + ":" + httpPass;
BASE64Encoder encoder = new BASE64Encoder();
String encodedStr = encoder.encode(userpass.getBytes());
String basicAuth = "Basic " + encodedStr;
try {
url = new URL(urlString);
conn = (java.net.HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Host", url.getHost());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.connect();
System.out.println("Headers: " + conn.getHeaderFields());
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
System.out.println("response code: " + responseCode + ", response message: " + responseMessage);
if (responseCode >= 400) {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String errorString = "";
while ((line = rd.readLine()) != null) {
errorString += line;
}
rd.close();
System.out.println("error stream: " + errorString);
} else {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
issueBody += line;
}
rd.close();
}
} catch (UnknownHostException e) {
OpenLogItem.logError(session, e, "java.net.UnknownHostException: Can't find specified host: "+urlString, Level.SEVERE, null);
issueBody = issue.getItemValueString("Body");
} catch (MalformedURLException e) {
OpenLogItem.logError(session, e, "java.net.MalformedURLException: Can't connect to invalid URL: "+urlString, Level.SEVERE, null);
issueBody = issue.getItemValueString("Body");
} catch (IOException e) {
OpenLogItem.logError(session, e, "java.io.IOException: Failed to read stream at: "+urlString, Level.SEVERE, null);
issueBody = issue.getItemValueString("Body");
} catch (NullPointerException e) {
OpenLogItem.logError(session, e, "java.lang.NullPointerException. Failed to establish HTTP connection. Header fields: "+conn.getHeaderFields()+" URL: "+urlString, Level.SEVERE, null);
issueBody = issue.getItemValueString("Body");
} catch (Exception e) {
OpenLogItem.logError(session, e, "Unknown error. Failed to establish HTTP connection: "+urlString, Level.SEVERE, null);
issueBody = issue.getItemValueString("Body");
} finally {
conn.disconnect();
}
Here is the stack trace:
java.lang.NullPointerException
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:719)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:646)
at COM.ibm.JEmpower.applet.http.HttpURLConnection.getInputStream(HttpURLConnection.java:411)
at COM.ibm.JEmpower.applet.http.HttpURLConnection.getHeaderField(HttpURLConnection.java:692)
at java.net.URLConnection.getContentType(URLConnection.java:509)
at JavaAgent.saveIssueToRedmine(Unknown Source)
at JavaAgent.pushIssueFromNotesToRedmine(Unknown Source)
at JavaAgent.NotesMain(Unknown Source)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(Unknown Source)

Categories