0

I'm trying to read custom error message I sent along an HTTP response for a web API project using Java.

Currently, I have this piece of Java code to read Header Response,

import java.net.HttpURLConnection;
import java.net.URL;

public class URLReader {
   public static void main(String[] args) throws Exception {
        URL oracle = new URL(URL);
        HttpURLConnection connection =(HttpURLConnection)oracle.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        System.out.println(connection.getHeaderField(0));
    }
}

An output of HTTP response header looks like this (Fiddler):

enter image description here

How can I get My Error Message text using Java?

1
  • To my understanding all you need is to assign a key to the header. like the other ones above yours and you will be able to use the key to retrieve the message. Commented Dec 22, 2016 at 13:46

3 Answers 3

2

@Abzal Kalimbetov is wrong about getErrorStream(), which will return an InputStream when an exception is raised, indicating response code >= 400 is received from the server.

Recap:

InputStream inputStream = null;
try {
    // normal operation
    inputStream = connection.getInputStream();
}
catch(IOException exception)
{
    inputStream = connection.getErrorStream();
    //@TODO you can now extract your custom error message from inputStream.
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your approach is not so good, you are trying to get inputstream while you know it is not there when the response code is 400
Response statue code >= 400 will be regarded as an exception in Java, not just 404 or 410, though they're of FileNotFoundException type, more specific one.
1

If the request status is greater than or equal 400, you use getErrorStream() method

  if(connection.getResponseCode()>=400){ 
       String myErrorMessage = connection.getErrorStream();
  }

1 Comment

Looking at implementation of HttpUrlConnection, errorStream is being used under this condition : responseCode >= 400. 1xx and 3xx status codes doesn't represent error states. Only 4xx (client error) or 5xx (server error) does.
-1

You can set a header in your server application which you then can read out very simple like this: ( Servlet usage is needed for this. )

private void test(ServletRequest request, ServletResponse response) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;

httpServletResponse.addHeader( "myErrorMessage", "this is the message" );
String message = httpServletRequest.getHeader( "myErrorMessage" );
}

if you don't have these resources available it is possible to get the message like this:

//get all headers
Map<String, List<String>> map = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    System.out.println("Key : " + entry.getKey() +
                 " ,Value : " + entry.getValue());
}

//get header by 'key'
String server = connection.getHeaderField("Server");

1 Comment

@Downvoter please be so kind and let me know why you downvoted so I can learn from it and improve my future answers and my general understanding of programming. Thanks...

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.