【问题标题】:Execute rest call in synchronous way using httpclient使用 httpclient 以同步方式执行 rest 调用
【发布时间】:2018-06-14 18:18:40
【问题描述】:

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

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

第二个休息呼叫应该只在第一个休息呼叫成功后进行。

有没有办法使用 HttpClient 来实现?

【问题讨论】:

  • 你可以简单地在第一个完成(回调)后开始第二个,不建议在主线程上同步,可以在同一个线程上按顺序进行

标签: java rest httpclient


【解决方案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();
    }

【讨论】:

  • 没问题,我的荣幸:)
猜你喜欢
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2014-05-01
相关资源
最近更新 更多