2016-11-09 62 views
1

我有一个httpClient函数,它将HttpResponse对象返回给调用函数。使用HttpResponse时出现socket关闭错误对象

public HttpResponse postRequest(String uri, String body) throws IOException { 
     HttpResponse response; 
     String url = baseUrl + uri; 
     try (CloseableHttpClient httpClient = HttpClientBuilder.create() 
       .build()) { 
      HttpPost post = new HttpPost(url); 
      post.setEntity(new StringEntity(body)); 
      post.setHeader(AUTHORIZATION_HEADER, authorization); 
      post.setHeader(CONTENTTYPE_HEADER, APPLICATION_JSON); 
      post.setHeader(ACCEPT_HEADER, APPLICATION_JSON); 

      response = httpClient.execute(post); 
     } catch (IOException e) { 
      System.out.println("Caught an exception" + e.getMessage().toString()); 
      logger.error("Caught an exception" + e.getMessage().toString()); 
      throw e; 
     } 
     return response; 
    } 

在我的呼唤功能我打电话,HttpResponse response = httpRequest.postRequest(url,body);(其中HttpRequest的是,包含了函数

当我试图通过

String responseString = IOUtils.toString(response.getEntity() 
        .getContent(), "UTF-8"); 
来解析所接收的响应内容的类的对象

我收到一个错误Socket is closed。

一旦连接关闭,我该如何使用HttpResponse的内容?

回答

0

您的try-with-resources语句将关闭整个客户端。你不想那样。去掉它。当呼叫者关闭你正在返回的响应时,你希望接近发生。

+0

你能举个例子吗。我没有跟着你 – user1692342

相关问题