如果响应时间超过n秒,是否可以在Java中重新运行HTTP post请求?

huangapple go评论154阅读模式
英文:

Rerun http post request if response time is longer than n seconds in Java?

问题

以下是您的代码的翻译部分:

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";
}
英文:

I am calling REST API with Java but there are occasional delays in the response sometimes. So I want to somehow check if the response is taking too long (for example 2 or 3 seconds) and restart/rerun the http post request, because I don't need a request that is "stuck" at waiting for a response which might come a lot, a lot later.

This is my piece of code so far:

private final CloseableHttpClient client;
HttpResponse response;
List&lt;NameValuePair&gt; parameters;
HttpPost post;

public String getRoleData(int roleid) {
	this.post = new HttpPost(this.createUrl(&quot;role/eventdata&quot;));
	this.post.setHeader(&quot;apikey&quot;, this.apikey);
	this.parameters = new ArrayList&lt;&gt;();
	this.parameters.add(new BasicNameValuePair(&quot;roleid&quot;, 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(&quot;API Unsupported instruction entry&quot;);
	} catch (IOException ex) {
		System.out.println(&quot;API IO issue&quot;);
	}
	return &quot;Empty response&quot;;
}

答案1

得分: 0

以下是您提供的Java代码的中文翻译部分:

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不支持的指令输入");
        } catch (IOException ex) {
            System.out.println("IO问题" + ex.getCause().getClass());
        }
    }
}

此外,以下是您提供的附加信息的中文翻译部分:

"这应该与上面的代码类似。请检查RequestConfig部分和异常处理部分。您可以在错误处理中添加一个标志,并重试。我们在这里为HTTP客户端设置了超时值。您可以查看一些Java文档以获取更多详细信息。

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

英文:
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(&quot;https://reqres.in/api/api/users&quot;);
//this.post.setHeader(&quot;apikey&quot;, this.apikey);
List&lt;NameValuePair&gt; parameters = new ArrayList&lt;NameValuePair&gt;();
parameters.add(new NameValuePair(&quot;name&quot;, &quot;test1&quot;));
parameters.add(new NameValuePair(&quot;job&quot;, &quot;job1&quot;));
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(&quot;API Unsupported instruction entry&quot;);
} catch (IOException ex) {
System.out.println(&quot;IO issue&quot; + ex.getCause().getClass());
}
}
}

It should be somewhat similar to above. Check RequestConfig part & Exception handling part. You can add a flag in error handling & retry again. We are setting up timeout values here for http client. You can go through some java doc for more details.

By the way, you are using POST method which is by definition not idempotent. So you need to be careful while rerunning the same request again. The server might have processed already after you got the timeout.

huangapple
  • 本文由 发表于 2020年9月16日 06:48:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63910823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定