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

I am getting a null response on passing this URL even though the same URL when opened on the browser shows a lot of stuff. I am getting a Null Pointer Exception. Please help. Below is my 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;
        }
    }
}

}

bene1337_
  • 71
  • 4
noor
  • 73
  • 1
  • 7
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – denvercoder9 Jun 30 '20 at 11:35
  • where you are getting null value? – darwin Jun 30 '20 at 11:36
  • in the mehod doInBackground..the result is null. I logged the result and checked it. – noor Jun 30 '20 at 11:38
  • you are returning null in catch block, so there should be an exception, try printing the exception and get the cause of issue – darwin Jun 30 '20 at 11:59

1 Answers1

0

You have to call connect method before reading the result or response code. Add the below line after setting up the request method

httpURLConnection.connect()
Alpha 1
  • 4,118
  • 2
  • 17
  • 23