Reading content from a URL failing

55 views Asked by At

I am trying to read a JSON from a web page and store it as a string, however when debugging it keeps failing in the try statement at line:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

public String networkRequest() throws IOException {

    URL url = new URL("https://graph.facebook.com/me");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try
    {
        InputStream inputStream = url.openStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        int cp;
        while ((cp = bufferedReader.read()) != -1)
        {
            stringBuilder.append((char) cp);
        }

        return stringBuilder.toString();
    }
    catch(Exception ex)
    {
        return "nothing";
    }
}

In which because of the fail reaches the catch and returns "nothing", does anyone understand what I am doing wrong?

BTW: My network is perfectly fine!

1

There are 1 answers

4
siva On

Great. It means you are executing this method from UI thread which is not recommended and android strict mode will not allow this. Hence there is an exception. Please execute the method from a background thread.