通过HTTPURLConnection请求Transfer-Enconding chunked

时间:2015-11-24 15:14:48

标签: java http httpurlconnection transfer-encoding

我试图从API的端点获取数据,我注意到我试图通过HTTP POST方法获取的数据非常庞大且API的服务器响应我将标题之一设置为Transfer-Encoding: chunked的响应,并且我想要读取整个数据。在我的代码中,我使用java.net.HttpURLConnection来建立我的发布请求并阅读下面显示的数据。

不幸的是,对于这种情况,我在java.io.IOException: Premature EOFBufferedReader)读取的行中收到了while((output = br.readLine()) != null)我调试了它并且我获得了状态http 200直到异常被抛出之前。

请求我的代码中显示的分块数据有什么问题吗?

谢谢。

String responseStr = "";
HttpURLConnection connection = null;
try {
     connection = (HttpURLConnection) new URL(this.url).openConnection();
     connection.setRequestProperty("content-type", "application/json");
     connection.setRequestProperty("Accept", "application/json");
     connection.setDoOutput(true);
     OutputStream os = connection.getOutputStream();
     os.write(payloadToBeRequested.getBytes());
     os.flush();

     BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String output = "";
     while((output = br.readLine()) != null){
         responseStr = responseStr + output;
     }
     status = connection.getResponseCode();
     connection.disconnect();
}catch(MalformedURLException ex){
     ex.printStackTrace();
}catch(IOException ex){
     ex.printStackTrace();
}

0 个答案:

没有答案