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

时间:2018-06-14 18:18:40

标签: java rest httpclient

我要一个接一个地执行两个休息呼叫。

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

第二次休息呼叫只应在第一次休息呼叫成功后继续。

有没有办法可以使用HttpClient实现这个目标?

1 个答案:

答案 0 :(得分:1)

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

 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();
    }