JSON retrieves url for Android

Friends, I had a problem when analyzing json content directly from the url specified by http://samplejson.com/transactions.json , but when I store the same url content as the text file in my res / raw, it also parses data, but when retrieving the contents of the URL from the network, an exception is displayed (i.e., the JSONArray text must begin with '[' on character 1 of ...

what is wrong here. Help me solve this problem.


URL url_net = new URL("http://samplejson.com/transactions.json"); 
InputStream is = url_net.openStream(); 
byte [] buffer = new byte[is.available()]; 
while (is.read(buffer) != -1); 
String jsontext = new String(buffer); 
JSONArray entries = new JSONArray(jsontext); 
x = "JSON parsed.\nThere are [" + entries.length() + "]\n\n"; 
int i; 
for (i=0;i<entries.length();i++) { }
+3
source share
1 answer

OK, your code seems to be reading all of HTTP, including the headers. That is why your does not start with "[".

Here is the code I use to return the HTTP GET string content:

public static String getStringContent(String uri) throws Exception {

    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(uri));
        HttpResponse response = client.execute(request);
        InputStream ips  = response.getEntity().getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));

        StringBuilder sb = new StringBuilder();
        String s;
        while(true )
        {
            s = buf.readLine();
            if(s==null || s.length()==0)
                break;
            sb.append(s);

        }
        buf.close();
        ips.close();
        return sb.toString();

        } 
    finally {
               // any cleanup code...
            }
        } 
+10
source

Source: https://habr.com/ru/post/1786126/


All Articles