Setting a timeout value when retrieving data via HttpGet object

13,781

try this instead

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","foobar"));
URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath",
URLEncodedUtils.format(params, "UTF-8"), null);

HttpGet httpGet = new HttpGet(uri);
HttpClient httpClient = new DefaultHttpClient();
// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
httpClient = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = httpClient.execute(httpGet);
String result = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

From Java HTTP Client Request with defined timeout

Share:
13,781

Related videos on Youtube

acvcu
Author by

acvcu

Updated on September 15, 2022

Comments

  • acvcu
    acvcu over 1 year

    I have some Java code that I 'inherited' from a previous co-worker. Part of it connects to an outside URL using method GET and retrieves a small amount of XML for parsing. We've been having issues recently with this connection crashing our website due to the vendor website hanging and using up resources on our side. One issue is due to no timeouts being set when our code uses the HttpGet object. Is there a way to fine-tune timeouts using this object, or is there a better way to pull back this XML?

    Would I be better off using another API?

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("param1","foobar"));
    URI uri = URIUtils.createURI("http", "myhost.com", -1, "mypath",
    URLEncodedUtils.format(params, "UTF-8"), null);
    
    // there is no timeout here??
    HttpGet httpGet = new HttpGet(uri);
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpGet);
    String result = IOUtils.toString(httpResponse.getEntity()
        .getContent(), "UTF-8");
    

    Thanks!

  • electrobabe
    electrobabe almost 6 years
    since DefaultHttpClient is deprecated use: HttpGet httpGet = new HttpGet(url.toURI()); HttpClient httpClient = HttpClientBuilder.create().setConnectionTimeToLive(30, TimeUnit.SECONDS).build(); HttpResponse httpResponse = httpClient.execute(httpGet);