HttpURLConnection getInputStream返回null

时间:2017-07-22 11:28:09

标签: java android httpurlconnection httpconnection

getInputStream()返回null。我搜索了它但无法得到任何帮助。谁能告诉你如何解决它?

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());
    }
}

1 个答案:

答案 0 :(得分:1)

使用我的代码,它对我有用。

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 = "";
 }