Http Get Request and set timeout / retry time in java

The following example will show how to send http request in java, from security consideration, we need to set timeout and retry times and some other import aspects.

  • main part

import org.apache.http.client.HttpRequestRetryHandler;

import org.apache.http.protocol.HttpContext;


import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public void process(String url) throws exception {

    // set timeout with 5 seconds.
    RequestConfig config = RequestConfig.custom().setConnectTimeout(5 * 1000).build();

    //use custom retry handler to make retry handler effect.
    CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(CustomRetryHandler.process()).setDefaultRequestConfig(config).build();

    //Build get request.
    HttpGet request = new HttpGet(url);

    //Execute request and get response.
    HttpGet request = new HttpGet(url);
    HttpResponse response = httpClient.execute(request);

    //Get response
    BufferedReader rd = new BufferedReader(new AInputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null)

    return result.toString();

  • Custom retry handler

public HttpRequestRetryHandler process() {

HttpRequestRetryHandler customRetryHandler = new HttpRequestRetryHandler() {

public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 3) {
        return false;
        return true;
    return customRetryHandler;

Reference to :











































电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>