【发布时间】: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