I am trying to send a request over a URLConnection using HttpUrlConnection
, which is working but the response code: 400
is being thrown when getting the response back with connection.getInputStream()
. The web Service I am writing to is sending large JSON response. In fact when I try small requests ( therefore small responses) the program works fine. Its a matter of size of response being too large.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.connect();
ObjectMapper mapper = new ObjectMapper();
//building the json request.. tested and works fine
String json = mapper.writeValueAsString(requestParameters);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); //Program throws exception here for large response
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
how can i improve my code in a way that it can be able to read large response from web service?
Your code is fine. If the server is returning 400 it means that it can't handle large requests, so the main fix has to be done in the server code.
If you want to make a shorter json we could help you if you show us that requestParameters, maybe we can figure out a way to split that json into shorter requests.
It would be useful too to see your e.stackPrintTrace(), or the connection.getErrorStream().