I am using Apache HttpClient 4.2.5 and need to set connection timeout for 30 seconds. I do the following:
int timeout = 30 * 1000;
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, timeout);
HttpClient client = new DefaultHttpClient(params);
HttpGet request = new HttpGet(url.toURI());
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
HttpResponse response = client.execute(request);
But after 12 seconds NoRouteToHostException is thrown form client.execute(request). As I understand, CONNECTION_TIMEOUT and SO_TIMEOUT is useless here. Have you any idea, how to set timeout for NoRouteToHostException? I should hope that server became available within this time. Thanks for any comment and advice!
Related
I want to call REST API by java programming. And I also want to give a time limitation during calling that API. If response time take more than 10 second than I want to disconnect API calling and print a message that response time is more than 10 second.
Please help me by given example code of java.
Given bellow the source code of calling API.
JSONParserPost jsonParserpost = new JSONParserPost();
String output = jsonParserpost.makeHttpRequest(URL, "POST", request);
System.out.println("Row output :"+ output.toString());
JSONObject jsonObject = new JSONObject(output);
if(jsonObject != null)
responeXML = (String)jsonObject.get("response");
Here in 2nd line I've called a REST API. Now I want to fixed a time limit on duration of response of REST API.
If you are using httpClient this following link can help you from my understanding of your problem. Apache HttpClient Timeout.
int CONNECTION_TIMEOUT_MS = timeoutSeconds * 1000; // Timeout in millis.
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();
HttpPost httpPost = new HttpPost(URL);
httpPost.setConfig(requestConfig);
1
URL url = new URL(this.serviceURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Accept", "application/xml;");
connection.setDoInput(true);
connection.setDoOutput(true);
/*
* connection timeout value to 20 seconds
*/
int apiReadTimeOut = 20; // 20 seconds
connection.setConnectTimeout(apiReadTimeOut * 1000);
connection.setReadTimeout(apiReadTimeOut * 1000);
2
HttpClient httpClient = null;
/*
* connection timeout value to 20 seconds
*/
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
httpClient = new DefaultHttpClient(httpParams);
You can use spring restTemplate
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(milisecond);
((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setReadTimeout(milisecond);
return restTemplate;
}
Please find example
- https://howtodoinjava.com/spring-boot2/resttemplate-timeout-example/
I want to get a web page but if return Connection refused I want to wait only 1 second
My code :
final DefaultHttpClient client = HTTPSHelper.getClientThatAllowAnyHTTPS(connectionManager);
client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setParameter("http.socket.timeout", 1000);
client.getParams().setParameter("http.connection.timeout", 1000);
client.addRequestInterceptor(new RequestAcceptEncoding());
client.addResponseInterceptor(new ResponseContentEncoding());
final HttpGet get = new HttpGet(url.getUrl());
final HttpResponse resp = this.httpClient.execute(get, localContext);
When returns connection refused I have to wait a lot ...Is there a way to specify time to wait on connection refused ? Thanks
You can set the timeout for the connection this way:
final HttpParams p = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(p, 1000);
client = new DefaultHttpClient(httpParams) ;
What is the right way for me to use the same TCP connection when using Apache HttpClient?
My code currently is:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();
for (int i = 0; i < 100; i++)
{
CloseableHttpResponse response = httpClient.execute(new HttpGet("http://www.google.co.uk"), httpContext);
String responseBody = EntityUtils.toString(response.getEntity());
EntityUtils.consume(response.getEntity());
response.close();
}
I have tried using the code with and without response.close() but the times vary each run that I can't figure out which one is keeping the connection open.
Can somebody please explain to me how I can keep the connection open?
So after messing around with TCPView I figured out that placing the lines:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpClientContext httpContext = HttpClientContext.create();
inside of the loop used a new TCP connection each time. Turns out that HttpClient will automatically try and reuse the connection for the same 'HttpClient' object.
I want to implement a setConnectionTimeout in my Android app. I've followed several code structures but couldn't make it work. My app was connected to a localhost server, I just want it to display Connection Timeout if it cannot be connected to the database.
Here is my Http Request code:
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
The problem is when it reaches 3 seconds, the app crashes. Before I implemented this snippet, it just freezes for a longer time. And if I turn off my Wifi, it will return a DialogBox saying that the internet is not connected, and this is what I want to achieve.
Any idea how to return an AlertDialogBox if database couldn't be connected? (I've disabled WAMP for this purpose)
Your exception is saying that there's a null pointer exception while parsing JSON. You didn't attach that code here, so I'm only assuming that once your timeout occurs, you're still trying to parse the input stream into JSON.
It would be good to check if your input stream isn't empty first.
I want to check if a web service is available before connecting to it, so that if it is not available, I can display a dialog that says so. My first attempt is this:
public void isAvailable(){
// first check if there is a WiFi/data connection available... then:
URL url = new URL("URL HERE");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(10000); // Timeout 10 seconds
connection.connect();
// If the web service is available
if (connection.getResponseCode() == 200) {
return true;
}
else return false;
}
And then in a separate class I do
if(...isAvailable()){
HttpPost httpPost = new HttpPost("SAME URL HERE");
StringEntity postEntity = new StringEntity(SOAPRequest, HTTP.UTF_8);
postEntity.setContentType("text/xml");
httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
httpPost.setEntity(postEntity);
// Get the response
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httpPost);
// Convert HttpResponse to InputStream for parsing
HttpEntity responseEntity = httpResponse.getEntity();
InputStream soapResponse = responseEntity.getContent();
// Parse the result and do stuff with the data...
}
However I'm connecting to the same URL twice, and this is inefficient and probably slowing down my code.
First of all, is it?
Secondly, what's a better way to do this?
I would just try connecting, if it times out, handle the exception, and display an error.
May be you should consider looking at HttpConnectionParams class methods.
public static void setConnectionTimeout (HttpParams params, int
timeout)
Sets the timeout until a connection is etablished. A value of zero
means the timeout is not used. The default value is zero.
public static void setSoTimeout (HttpParams params, int timeout)
Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is
the timeout for waiting for data. A timeout value of zero is
interpreted as an infinite timeout. This value is used when no socket
timeout is set in the method parameters.
Hope this helps.
As above and here is how you check for times out:
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
And then pass the HttpParameters to a constructor of httpClient:
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);