Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection: Difference between getResponseMessage(), getInputStream() and getContent()

Team,

I have come across the code like below,

private static String getResponse (HttpURLConnection connection) throws Exception
{
   String responseString = null;
   int responseCode = connection.getResponseCode();
   String responseMessage = connection.getResponseMessage();
   Log.debug("%s - Response code is \"%s\" with message \"%s\"",
          methodName, responseCode, responseMessage);
   String line = null;
   if (responseCode == HttpURLConnection.HTTP_OK) {
       BufferedReader bufferedReader = null;
       try {
           InputStream inputStream = connection.getInputStream();
           if (inputStream != null) {
               bufferedReader = Util.bufferedReader(
                   inputStream, Util.Encod.UTF8);
               StringBuilder response = new StringBuilder();
               while ((line = bufferedReader.readLine()) != null) {
                   response.append(line);
                   response.append(Util.getNewLine());
               }
               responseString = response.toString();
           }
       }
       finally {
           if (bufferedReader != null) {
               bufferedReader.close();
           }
       }
       Log.signature.debug(
           "%s - Received following JSON response : %s",
           methodName,
           responseString);
   }
   return responseString;
} 

Here they have already received the response like below right?

String responseMessage = connection.getResponseMessage()

Then why they are again using connection.getInputStream()

Is there any difference?

If possible could you please also explain some example OR when to use the below than the above getResponseMessage() / getInputStream()

Class URLConnection 
   public Object getContent() throws IOException 
   public Object getContent(Class[] classes) throws IOException
like image 543
Kanagavelu Sugumar Avatar asked Apr 17 '26 11:04

Kanagavelu Sugumar


1 Answers

getResponseMessage() is used for getting the message for the connection like HTTP_NOT_FOUND

HTTP Status-Code 404: Not Found.

For getting the actual data you have to through getInputStream() please find below details:

public InputStream getInputStream() throws IOException

Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

Returns: an input stream that reads from this open connection.

Throws: IOException - if an I/O error occurs while creating the input stream. UnknownServiceException - if the protocol does not support input.

Please refer following link for more details : http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()

like image 171
vishal parmar Avatar answered Apr 18 '26 23:04

vishal parmar