0

I want to know if there is an error response when sending the REST POST request, and i want to print the error as "output" in my Java application.

How do i do this?

Here is the code I'm using:

    HttpClient client = new HttpClient();

    try {
    HttpPost request = new HttpPost("example.com/api/deposit");
    StringEntity params;
    params = new StringEntity("{"
    + "\"locale\": \"" + exampleclass.getLocale() + "\","
    + "\"dateFormat\": \"" + exampleclass.getDateFormat() + "\","
    + "\"transactionDate\": \"" + exampleclass.getTransactionDate() + "\","
    + "\"transactionAmount\": \"" + exampleclass.getTransactionAmount() + "\","
    + "}");
    request.addHeader("Content-Type", "application/json");
    request.addHeader("Accept-Language", "en-US,en;q=0.8");
    request.addHeader("Authorization", "Basic somecode&&!!");
    request.setEntity(params);
    HttpResponse response = client.execute(request);

    //handle the response somehow
    //example : System.out.println (errormessage);

    } catch (Exception ex) {
    ex.printStackTrace();
    ex.getMessage();
    } finally {
    client.getConnectionManager().shutdown();

    }

Any help is greatly appreciated!

2 Answers 2

2

You should be able to read the returned HTTP status code in the HttpResponse response.

response.getStatusLine().getStatusCode()

return the HTTP code, 200 means OK, another code indicate error.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't see anything in my output window except " build successful ", I want to see the HTTP status code as you mentioned + the reason why, for example " account with identifier 15 does not exist ".
You can debug your code to inspect returned value at runtime, error code have associated reason defined see [rfc2616] (w3.org/Protocols/rfc2616/rfc2616-sec6.html), any other information provided is specific for the server, see eventual documentation for the web service
Thank you for this line of code, it was helpful eventhough it wasn't entirely what I was looking for, upvote
1

You can use something as below:-

    String line = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(getResponse.getEntity().getContent()));
            while ((line = rd.readLine()) != null)
            {
                System.out.println(line);
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.