Skip to content

Instantly share code, notes, and snippets.

@nickhargreaves
Created July 18, 2015 19:06
Show Gist options
  • Save nickhargreaves/8d32212c29a046caa42f to your computer and use it in GitHub Desktop.
Save nickhargreaves/8d32212c29a046caa42f to your computer and use it in GitHub Desktop.
Android JSON Parser
package com.pushapp.tests;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url_, List<NameValuePair> params) {
// Making HTTP request
try {
HttpClient defaultClient = HttpClientBuilder.create().build();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url_);
httpGetRequest.setHeader("Accept", "application/json; charset=utf-8");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.d("response", is.toString() + "");
//read response
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
// return JSON String
return jObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment