0

I'm trying to get data from a API's endpoint and I have noticed the data I'm trying to get by HTTP POST method is huge and the API's server respond me with a response with one of headers set as Transfer-Encoding: chunked and I'd like to read the whole data. In my code I'm using the java.net.HttpURLConnection to establish my post request and read the data as showed bellow.

Unfortunately for this scenario I'm getting java.io.IOException: Premature EOF at the line where I read from the BufferedReader(while((output = br.readLine()) != null)) I debugged it and I'm getting status http 200 until right before the Exception has been threw.

Is there anything wrong in requesting chunked data like showed in my code?

Thank you.

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();
}
Saulo Ricci
  • 776
  • 1
  • 8
  • 27
  • try to put `status = connection.getResponseCode();` above `BufferedReader br = ...`. Log the response code. Is it 200 or 5xx or 4xx? – hgoebl Nov 24 '15 at 16:03
  • @hgoebl Interesting the fact I still got 200 if I replace the status before the BufferedReader. What do you think about that? – Saulo Ricci Nov 24 '15 at 16:21
  • Try to use one of the [comfort-libraries](http://hgoebl.github.io/DavidWebb/#background) and see if you have more luck. I don't see any problems in your code, but `HttpURLConnection` is a beast somehow. BTW are you sure your server delivers content with a linefeed? Maybe `br.readLine()` refuses to return a line if there is no linefeed?! – hgoebl Nov 24 '15 at 21:32
  • @hgoebl thanks. I did a modification to consider just read to an array of char and controlling the size of read chars, instead of readLine(), and unfortunately I got the same results. I'll take a look on other libraries for sure. – Saulo Ricci Nov 24 '15 at 23:47

0 Answers0