簡體   English   中英

Json 新聞結果 API 是 null

[英]Json Result from News API is null

 @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 時收到 null 響應,即使在瀏覽器上打開相同的 URL 時顯示很多東西。 我收到 Null 指針異常。 請幫忙。 下面是我的 HttpRequest class。

HTTPRequest Class:

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

}

您必須在讀取結果或響應代碼之前調用 connect 方法。 設置請求方法后添加以下行

httpURLConnection.connect()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM