Search code examples
javaandroidhttpurlconnectionhttpconnection

HttpURLConnection getInputStream returns null


getInputStream() is returning null. I searched for it but couldn't get any help. Can anyone please tell how to resolve it?

HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setReadTimeout(100000 /* milliseconds */);
    urlConnection.setConnectTimeout(150000 /* milliseconds */);
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    // If the request was successful (response code 200),``
    // then read the input stream and parse the response.
    if (urlConnection.getResponseCode() == 200) {
        inputStream = urlConnection.getInputStream();
        jsonResponse = readFromStream(inputStream);
    } else {
     //   Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
    }
}

Solution

  • Use my code it's working for me.

    String response;
    
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setReadTimeout(10000);
    connection.setConnectTimeout(10000);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    int responceCode = connection.getResponseCode();
    
    if (responceCode == HttpURLConnection.HTTP_OK)
    {
         String line;
         BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         while ((line = br.readLine()) != null)
         {
              response = "";// String variable declared global
              response += line;
              Log.i("response_line", response);
         }
     }
     else 
     {
          response = "";
     }