【问题标题】:Rerun http post request if response time is longer than n seconds in Java?如果Java中的响应时间长于n秒,则重新运行http post请求?
【发布时间】:2020-09-15 22:48:18
【问题描述】:

我正在使用 Java 调用 REST API,但有时响应有时会出现延迟。所以我想以某种方式检查响应是否花费太长时间(例如 2 或 3 秒)并重新启动/重新运行 http post 请求,因为我不需要“卡住”等待响应的请求,这可能来很多,很晚。

到目前为止,这是我的一段代码:

private final CloseableHttpClient client;
HttpResponse response;
List<NameValuePair> parameters;
HttpPost post;

public String getRoleData(int roleid) {
    this.post = new HttpPost(this.createUrl("role/eventdata"));
    this.post.setHeader("apikey", this.apikey);
    this.parameters = new ArrayList<>();
    this.parameters.add(new BasicNameValuePair("roleid", String.valueOf(roleid)));
    try {
        post.setEntity(new UrlEncodedFormEntity(this.parameters));
        this.response = client.execute(post);
        String JsonResponse = EntityUtils.toString(this.response.getEntity(), StandardCharsets.UTF_8);
        return JsonResponse;
    } catch (UnsupportedEncodingException ex) {
        System.out.println("API Unsupported instruction entry");
    } catch (IOException ex) {
        System.out.println("API IO issue");
    }
    return "Empty response";
}

【问题讨论】:

    标签: java api rest time response


    【解决方案1】:
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.nio.charset.StandardCharsets;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.util.EntityUtils;
    
    public class Test {
    
        public static void main(String[] args) {
            int timeoutInMillis = 10;
            RequestConfig config = RequestConfig.custom().
                  setConnectTimeout(timeoutInMillis).
                  setConnectionRequestTimeout(timeoutInMillis).
                  setSocketTimeout(timeoutInMillis).build();
            final CloseableHttpClient client = HttpClientBuilder.create()
                      .setDefaultRequestConfig(config).build();
            HttpPost post = new HttpPost("https://reqres.in/api/api/users");
            //this.post.setHeader("apikey", this.apikey);
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new NameValuePair("name", "test1"));
            parameters.add(new NameValuePair("job", "job1"));
            try {
                //post.setEntity(new UrlEncodedFormEntity(this.parameters));
                HttpResponse response = client.execute(post);
                String jsonResponse = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                System.out.println(jsonResponse);
            } catch (UnsupportedEncodingException ex) {
                System.out.println("API Unsupported instruction entry");
            } catch (IOException ex) {
                System.out.println("IO issue" + ex.getCause().getClass());
            }
        }
    }
    

    应该和上面有点类似。检查 RequestConfig 部分和异常处理部分。您可以在错误处理中添加标志并重试。我们在这里为 http 客户端设置超时值。您可以通过一些 java doc 了解更多详细信息。

    顺便说一句,您使用的 POST 方法根据定义不是幂等的。因此,再次重新运行相同的请求时需要小心。超时后服务器可能已经处理完毕。

    【讨论】:

    • 我试过这个例子,但它根本不起作用。 image link
    • @IndiFFer3nT 你能发布整个代码吗?您还可以更具体地说明什么不起作用吗?我猜你的意思是它不会在 3 秒左右后抛出错误。
    • 好吧,代码正是你告诉我的。我刚刚添加了一个 while 循环,以便在回答时间超过 3 秒时可以重试请求。 (就像我给你看上面的图片)。但是在这些新的更改之后,该程序不起作用。它给出了 Error parsing Role JSON from API Exception in thread "Thread-4" java.lang.NullPointerException 这意味着没有完全收到响应或响应为空,我不确定到底是哪个。
    • @IndiFFer3nT 在没有完整代码的情况下无法调试,看起来像是一个单独的问题。无论如何,我已经用一个完整的工作类更新了上面的代码,你可以参考它。发生超时时检查打印的异常类名称。您可以使用“timeoutInMillis”字段增加超时。然后你会得到正确的 json 响应。希望这会有所帮助。
    • 嗯,你能告诉我,如果达到超时,哪部分代码负责重试http请求?
    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2011-01-12
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2017-10-05
    相关资源
    最近更新 更多