Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class JSONParser {
- //variables
- static InputStream in = null;
- static JSONObject jObject = null;
- static String jsonString = "";
- // constructor
- public JSONParser() { }
- // function get json from url by making HTTP request POST or GET
- public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
- // creating HTTP request
- try {
- // check for type of requested method
- if(method == "POST"){
- // requested method - POST
- DefaultHttpClient client = new DefaultHttpClient();
- HttpPost post = new HttpPost(url);
- post.setEntity(new UrlEncodedFormEntity(params));
- HttpResponse response = client.execute(post);
- HttpEntity entity = response.getEntity();
- in = entity.getContent();
- }else if(method == "GET"){
- // requested method i- GET
- DefaultHttpClient client = new DefaultHttpClient();
- String paramString = URLEncodedUtils.format(params, "utf-8");
- url += "?" + paramString;
- HttpGet get = new HttpGet(url);
- HttpResponse httpResponse = client.execute(get);
- HttpEntity entity = httpResponse.getEntity();
- in = entity.getContent();
- }
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- //reading data
- BufferedReader readerBuffer = new BufferedReader(new InputStreamRea-der(in, "iso-8859-1"), 8);
- StringBuilder stringBuild = new StringBuilder();
- String line = null;
- while ((line = readerBuffer.readLine()) != null) {
- stringBuild.append(line + "\n");
- }
- in.close();
- jsonString = stringBuild.toString();
- } catch (Exception e) {
- Log.e("Buffer Error", "Error while converting" + e.toString());
- }
- // parsing the string to a JSON object
- try {
- jObject = new JSONObject(jsonString);
- } catch (JSONException e) {
- Log.e("JSON Parser", "Error parsing data " + e.toString());
- }
- // return JSON Object
- return jObject;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement