Skip to content

Instantly share code, notes, and snippets.

@mikelopez
Created August 12, 2011 23:10
Show Gist options
  • Save mikelopez/1143194 to your computer and use it in GitHub Desktop.
Save mikelopez/1143194 to your computer and use it in GitHub Desktop.
rest json parse
/* developed by Marcos Lopez 2011
* www.priceswagger.com
* dev@scidentify.info
*/
package com.priceswagger.apps.pricecompare;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
public class RestJSONClient {
// string representation of the json or error message
public String result_data = "";
public JSONObject json;
public JSONArray jsonArray;
public void searchProduct() {
String json_url = "http://192.168.0.10:8420/web/api/test_json/";
connect(json_url);
}
public void connect(String url)
{
// this will make an HTTP connection and get the response string
// It will also attempt to convert it to jsonarray
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
JSONObject json = new JSONObject();
try {
response = httpclient.execute(httpget);
result_data = response.toString();
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
result_data = result;
//json = new JSONObject(result);
try {
json = new JSONObject(result_data);
jsonArray = json.getJSONArray("items");
} catch (JSONException e) {
json = new JSONObject();
jsonArray = new JSONArray();
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result_data = "error clientprotocolexception";
} catch (IOException e) {
e.printStackTrace();
result_data = "error_ioexception";
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment