Retrieving JSON from URL on 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?
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
}
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
use org.json.JSONObject as in
JSONObject json = new JSONObject(oage);
thing to watch out for is when the response is simply "true" or "false." probably want to create a util function that checks for those cases, otherwise just load up the JSONObject.
ok in this case you would use a JSONArray
JSONArray jsonArray = new JSONArray(page);
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject element = jsonArray.getJSONObject(i);
.....
}
Have you tried setting the content type to application/json
?
Assume that we have a POJO class called Post
public List<Post> getData(String URL) throws InterruptedException, ExecutionException {
//This has to be AsyncTask because data streaming from remote web server should be running in background thread instead of main thread. Or otherwise your application will hung while connecting and getting data.
AsyncTask<String,String, List<Post>> getTask = new AsyncTask<String,String,List<Post>>(){
@Override
protected List<Post> doInBackground(String... params) {
List<Post> postList = new ArrayList<Post>();
String response = "";
try{
//Read stream data from url START
java.net.URL url = new java.net.URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
response += line + "\n";
}
//Read stream data from url END
//Parsing json data from reponse data START
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
String message = jsonArray.getJSONObject(i).getString("message");
// Post class has a constructor which accept message value.
postList.add(new Post(message));
}
//Parsing json data from reponse data END
} catch (Exception e){
e.printStackTrace();
}
return postList;
}
protected void onPostExecute(String result) {
}
};
//This will return a list of posts
return getTask.execute(URL).get();
}
just try like
///...
JSONArray jsonArray = new JSONArray(responseString);
for(JSONObject jsonObject:jsonArray)
{
.........
}
////..
精彩评论