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();
}