【问题标题】:Json Result from News API is null来自新闻 API 的 Json 结果为空
【发布时间】:2020-10-20 16:50:24
【问题描述】:
 @Override
    protected String doInBackground(String... strings) {
        String result = HttpRequest.getExecute("http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-30&sortBy=publishedAt&apiKey=myAPIkey");
        return result;
    }

即使在浏览器上打开相同的 URL 时显示很多内容,我在传递此 URL 时仍收到空响应。我收到空指针异常。请帮忙。下面是我的 HttpRequest 类。

HTTPRequest 类:

public class HttpRequest   {
public static String getExecute(String targetUrl)
{
    URL url;
    HttpURLConnection httpURLConnection = null;
    try
    {
        url = new URL(targetUrl);
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");

        InputStream inputStream;
        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)

            inputStream = httpURLConnection.getErrorStream();
        else
            inputStream = httpURLConnection.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuffer response = new StringBuffer();
        while ( (line = bufferedReader.readLine()) != null)
        {
            response.append(line);
            response.append('\r');

        }
        bufferedReader.close();
        return  response.toString();


    }
    catch (Exception e)
    {
     e.printStackTrace();
     return  null;
    }
    finally {
        if(httpURLConnection != null)
        {
            httpURLConnection = null;
        }
    }
}

}

【问题讨论】:

  • 你在哪里得到空值?
  • 在方法 doInBackground..结果为空。我记录了结果并检查了它。
  • 你在 catch 块中返回 null,所以应该有一个异常,尝试打印异常并找出问题的原因

标签: java android json api http


【解决方案1】:

您必须在读取结果或响应代码之前调用 connect 方法。设置请求方法后添加以下行

httpURLConnection.connect()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多