Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help on URL connection Timeout Setings!!

 
kamal shah
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using “java.net.HttpURLConnection” method to establish the connection. When it connects with URL and receiving no response from host, the program will hang for indefinite time.

The JDK version used is 1.4. I am seeking for the solution to define timeout at the time of connection creation. So that if scheduler will not receive any response, it will come out form the program at defined time.

Code Used for connection:

**********************************************************************************************************
URL url = new URL(stURL);
HttpURLConnection conHttp = (HttpURLConnection)url.openConnection();


conHttp.setDoOutput(true);
conHttp.setRequestMethod("POST");
conHttp.setRequestProperty("Content-Type","text/xml");
conHttp.setRequestProperty("Authorization","Basic " + encoding);


conHttp.setUseCaches(true);
OutputStream outputStream = conHttp.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream);
String xmlContent = strToPost;

writer.println(xmlContent);
writer.flush();
outputStream.close();


responseCode=conHttp.getResponseCode(); // when no response, program hangs at this statement.
if(responseCode>=203 && responseCode<=505)
{
//do something
}

InputStream inputStream = conHttp.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

String xmlResult = "";
while ((xmlResult = br.readLine()) != null)
{
resp+=xmlResult+"\n";
}
***************************************************************************************************************





I have tried the below solution but it didn’t work:
I have tried to set the below properties for the timeout, it is working fine with HTTP Protocol (http url’s) but doesn’t work with HTTPS(https url’s).

1.sun.net.client.defaultConnectTimeout (default: -1)
2.sun.net.client.defaultReadTimeout (default: -1)

Please revert if you have faced the same problem or you have any idea/ solution for this issue.

Thanks n regards,
Kamal
 
Dipanjan Kailthya
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to consider the apache httpclient, which seems to have the timeout functionality.

There is a solution posted herefor the HTTPURLConnection problem but it looks clunky to me...

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic