0

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?

bcsta
  • 1,963
  • 3
  • 22
  • 61
  • Are you sure it is because large response? I googled 400 response code,it is said bad request.So I guess your large request may have some syntax errors(it is not a valid json),you can output it and test if it is a valid json.See this [question](https://stackoverflow.com/questions/19671317/400-bad-request-http-error-code-meaning) – lin Feb 21 '18 at 11:35
  • I wil try that however the exception is being thrown on connection.getInputStream() not before when I request to the server – bcsta Feb 21 '18 at 11:46
  • @ChaojunZhong i just validated the json and it is valid. thereis no problem with my request. – bcsta Feb 21 '18 at 11:49

1 Answers1

1

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().

Carlos López Marí
  • 1,432
  • 3
  • 18
  • 45