gpt4 book ai didi

java - 使用httpclient以同步方式执行rest调用

转载 作者:行者123 更新时间:2023-11-30 06:08:04 25 4
gpt4 key购买 nike

我必须一个接一个地执行两个休息调用。

//first rest call
httpClient.execute(.....)
//second rest call, should only execute after successful completion of the
//first restcall
httpClient.execute(.....)

第二个休息调用只能在第一个休息调用成功后继续。

有没有办法使用 HttpClient 来实现这一点?

最佳答案

您只需将第二个调用放入第一个响应处理程序中,例如:

 try {
HttpGet httpget = new HttpGet("http://httpbin.org/");
HttpGet httpget1 = new HttpGet("http://httpbin.org/");

System.out.println("Executing request " + httpget.getRequestLine());

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
if(entity != null){
httpclient.execute(httpget1, responseHandler1);
}else{
return "No response";
}
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}

};

ResponseHandler<String> responseHandler1 = new ResponseHandler<String>() {

@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}

};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}

关于java - 使用httpclient以同步方式执行rest调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com