Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving JSON from URL on Android

Tags:

json

android

My phone APP downloads content perfectly in a text mode. Below is a code to do that. I call Communicator class and exectueHttpGet:

URL_Data = new Communicator().executeHttpGet("Some URL");

public class Communicator {
public String executeHttpGet(String URL) throws Exception 
{
    BufferedReader in = null;
    try 
    {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
        HttpGet request = new HttpGet();
        request.setHeader("Content-Type", "text/plain; charset=utf-8");
        request.setURI(new URI(URL));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";

        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) 
        {
            sb.append(line + NL);
        }
        in.close();
        String page = sb.toString();
        //System.out.println(page);
        return page;
    } 
    finally 
    {
        if (in != null) 
        {
            try 
            {
                in.close();
            } 
            catch (IOException e)    
            {
                Log.d("BBB", e.toString());
            }
        }
    }
}
}

What I recive is this (source code of URL):

[{"id_country":"3","country":"AAA"},{"id_country":"8","country":"BBB"},
{"id_country":"66","country":"CCC"},{"id_country":"14","country":"DDD"},
{"id_country":"16","country":"EEE"},{"id_country":"19","country":"FFF"},
{"id_country":"24","country":"GGG"},{"id_country":"33","country":"HHH"},
{"id_country":"39","country":"III"},{"id_country":"44","country":"JJJ"},
{"id_country":"45","country":"KKK"},{"id_country":"51","country":"LLL"},
{"id_country":"54","country":"MMM"},{"id_country":"55","country":"NNN"},
{"id_country":"57","country":"OOO"},{"id_country":"58","country":"PPP"},
{"id_country":"63","country":"RRR"},{"id_country":"65","country":"SSS"}]

This response is a String. On server it is outputted (with PHP) as JSON object and now in my Android PHP I want to transfrom this string to JSON. Is this possible?

like image 206
M.V. Avatar asked Apr 07 '11 08:04

M.V.


People also ask

How do I get JSON format from URL?

In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json. loads() to convert the response into a JSON object.


2 Answers

What you receive is a series of characters from the InputStream that you append to a StringBuffer and convert to String at the end - so the result of String is ok :)

What you want is to post-process this String via org.json.* classes like

String page = new Communicator().executeHttpGet("Some URL");
JSONObject jsonObject = new JSONObject(page);

and then work on jsonObject. As the data you receive is an array, you can actually say

String page = new Communicator().executeHttpGet("Some URL");
JSONArray jsonArray = new JSONArray(page);
for (int i = 0 ; i < jsonArray.length(); i++ ) {
  JSONObject entry = jsonArray.get(i);
  // now get the data from each entry
}
like image 186
Heiko Rupp Avatar answered Nov 07 '22 23:11

Heiko Rupp


EDIT:

To further the question I linked you to earlier, use this example. put it in a function that returns a JSONArray (so then you can loop through the array and use array.getString). This works for most amounts of data. It will send the correct compression headers to the web server and detect a gzip compressed result also. Try it:

    URL url = new URL('insert your uri here');
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setRequestProperty("Accept-Encoding", "gzip");
    HttpURLConnection httpConn = (HttpURLConnection) urlConn;
    httpConn.setAllowUserInteraction(false);
    httpConn.connect();
    if (httpConn.getContentEncoding() != null) {
        String contentEncoding = httpConn.getContentEncoding().toString();
        if (contentEncoding.contains("gzip")) {
        in = new GZIPInputStream(httpConn.getInputStream());
        }
        // else it is encoded and we do not want to use it...
    } else {
        in = httpConn.getInputStream();
    }
    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayBuffer baf = new ByteArrayBuffer(1000);
    int read = 0;
    int bufSize = 1024;
    byte[] buffer = new byte[bufSize];
    while (true) {
        read = bis.read(buffer);
        if (read == -1) {
        break;
        }
        baf.append(buffer, 0, read);
    }
    queryResult = new String(baf.toByteArray());
    return new JSONArray(queryResult);

/End Edit

Try reading the solution I posted on this SO question:

Create list in android app

Hth,

Stu

like image 20
Stuart Blackler Avatar answered Nov 07 '22 23:11

Stuart Blackler