HttpURLConnection getInputStream возвращает значение null

getInputStream() возвращает ноль. Я искал его, но не мог получить никакой помощи. Может ли кто-нибудь сказать, как это решить?

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

person zohaib    schedule 22.07.2017    source источник
comment
Можем ли мы увидеть полную трассировку стека ошибок?   -  person Ziyad Edher    schedule 22.07.2017


Ответы (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 = "";
 }
person Mahesh Gawhane    schedule 22.07.2017
comment
связан ли getInputStream() с URL-адресом API? - person zohaib; 22.07.2017
comment
Это ПОСТ. ОП хочет сделать GET. - person user207421; 22.07.2017
comment
@MaheshGawhane Найдите setDoOutput(), прежде чем обсуждать это дальше. - person user207421; 22.07.2017
comment
@MaheshGawhane спасибо. Ваш код решил мою проблему. - person zohaib; 22.07.2017
comment
@EJP я не знаю, что setDoOutput () используется для публикации .. спасибо, чтобы обновить меня - person Mahesh Gawhane; 26.07.2017