来自新闻 API 的 Json 结果为空
Posted
技术标签:
【中文标题】来自新闻 API 的 Json 结果为空【英文标题】:Json Result from News API is null 【发布时间】: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;
【问题讨论】:
这能回答你的问题吗? What is a NullPointerException, and how do I fix it? 你在哪里得到空值? 在方法 doInBackground..结果为空。我记录了结果并检查了它。 你在 catch 块中返回 null,所以应该有一个异常,尝试打印异常并找出问题的原因 【参考方案1】:您必须在读取结果或响应代码之前调用 connect 方法。设置请求方法后添加以下行
httpURLConnection.connect()
【讨论】:
以上是关于来自新闻 API 的 Json 结果为空的主要内容,如果未能解决你的问题,请参考以下文章
jQuery Mobile 中来自 Wordpress JSON 的新闻页面
带有来自w网站阅读器(rss、json)的新闻并显示用户(通知、存储)的应用程序