Home > database >  Java HTTPURLConnection - Reading error response from code 400 with payload
Java HTTPURLConnection - Reading error response from code 400 with payload

Time:08-17

I am trying to call an API that gives 400 on some requests.

But it has meaningful message that needs to be read. Also i am passing a payload(json body) in the api call

My code(it takes a payload as json) and the 400 response is below I am able to successfully read the response of 200 but issue is with 400

public static void blahblah (String input, String CustomerID, String endpoint, String dateNameFolder) throws UnknownHostException
            {
        
        

        try {
            
        
            
            
            
            URL url = new URL(endpoint);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
     
         
     
            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();
     
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));
            StringBuilder sb = new StringBuilder();
     
            String output;
          
            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
            
            File fileObj = new File(CustomerID   ".json");

            if (!fileObj.exists()) {
                fileObj.createNewFile();
                FileWriter dataWriter = new FileWriter(CustomerID   ".json");
                dataWriter.write(sb.toString());
                dataWriter.close();
            } else {
                FileWriter dataWriter = new FileWriter(CustomerID   ".json");
                dataWriter.write(sb.toString());
                dataWriter.close();
            }
     
            conn.disconnect();
     
            }catch (MalformedURLException e) {
     
                         
                l
                log.info(e);
          } 
          catch (IOException e) {
              
              
           log.error("Error in Validating Request to Catalog for Customer ID(400 Bad Request) : "   CustomerID ) ;
           log.info(e);
     
         }
    
    }

Sample output of 400 bad request :

<Response>
    <StatusCode>BadRequest</StatusCode>
    <ErrorCode>OrderRequestInvalid.InvalidCharacteristicUse</ErrorCode>
    <Message>Characteristic ID cannot be found in the specification: { EntityUniqueCode: CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0, CharacteristicID: 76c4e767-ce7b-4675-a178-d832839b322f}</Message>
    <Context>
        <EntityUniqueCode>CS_0aefdfec-022e-4ac9-a84b-83c8ea2e0fd0</EntityUniqueCode>
        <CharacteristicID>76c4e767-ce7b-4675-a178-d832839b322f</CharacteristicID>
    </Context>
</Response>

CodePudding user response:

You need to choose correct stream depending on your response status. here is an example how you can do this:

    BufferedReader br = null;
    int statusCode = conn.getResponseCode();

    if (statusCode>299){
        br = new BufferedReared(new InputStreamReader(conn.getErrorStream()));
    } else {
        br = new BufferedReared(new InputStreamReader(conn.getInputStream()));
    }
  • Related