2016-11-09 187 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

相關問題