1

I am having some issues with the following code. I am trying to read from the following Reddit URL

https://www.reddit.com/r/earthporn/.json?after=

Here is the code that is not correctly being executed.

public static String readContents(String url){
        try{
        InputStream input= new URL(url).openStream();
        Reader reader = new InputStreamReader(input);
        BufferedReader in = new BufferedReader(reader);
        String line, str;
        str = "";
        while ((line=in.readLine()) != null) {
            str += line;
            System.out.println(line);
        }
        return str;
        }catch(IOException e){
            Log.d("READ FAILED", e.toString());
            return null;
        }
    }
}

And here is where I call it from

List<Post> fetchPosts(){
    String raw=RemoteData.readContents(url);
    List<Post> list=new ArrayList<Post>();
    try{
        JSONObject data=new JSONObject(raw).getJSONObject("data");
        JSONArray children=data.getJSONArray("children");

        //Using this property we can fetch the next set of
        //posts from the same subreddit
        after=data.getString("after");

        for(int i=0;i<children.length();i++){
            JSONObject cur=children.getJSONObject(i)
                    .getJSONObject("data");
            Post p=new Post();
            p.title=cur.optString("title");
            p.url=cur.optString("url");
            p.numComments=cur.optInt("num_comments");
            p.points=cur.optInt("score");
            p.author=cur.optString("author");
            p.subreddit=cur.optString("subreddit");
            p.permalink=cur.optString("permalink");
            p.domain=cur.optString("domain");
            p.id=cur.optString("id");
            p.thumbnail=cur.optString("thumbnail");
            if(p.title!=null)
                list.add(p);
        }
    }catch(Exception e){
        Log.e("fetchPosts()",e.toString());
    }
    return list;
}

When debugging I get the following results: Raw is left empty. enter image description here

Does anyone have any clue as to why this it is not reading anything? I hope I included enough code for it to make sense. If anymore is needed, please let me know.

Jeremy Rowler
  • 387
  • 1
  • 5
  • 15
  • Nor really related but `str = ""; while ((line=in.readLine()) != null) { str += line; ...` is very bad idea if you are reading long file. Don't build String result in loop using concatenation since each time you call `a=a+"b"` Java needs to create StringBuilder which will copy old value, append new part and then create new String based on that content (which requires another iteration). It is better to create one StringBuilder before loop, `append` all parts in loop and finally convert it `toSring()`. – Pshemo Mar 28 '17 at 20:52
  • Are you getting a specific error or is it just empty? – sam_c Mar 28 '17 at 21:32
  • Since HttpClient is deprecated, [here's a good example](https://stackoverflow.com/a/48426408/2263683) of how to do it using URLConnection; – Ghasem Jan 24 '18 at 15:57

1 Answers1

1

Hello to get response you must open an HttpsURLConnection the problem that you have is you getting a null response from the URL so you must here is the code that works for me :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.MalformedURLException;
import java.net.URL;


import javax.net.ssl.HttpsURLConnection;


public class main {
    public static String getJSON(String url) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {

        String url = "https://www.reddit.com/r/earthporn/.json?after=";
        System.out.println(getJSON(url));

    }

}