Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.xyz.dbapp;
- import android.net.Uri;
- import android.util.Log;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- /**
- * Created by selvakumar on 4/29/2015.
- */
- public class JSONParser
- {
- static JSONObject jObj = null;
- static String json = "";
- public static final int CONNECTION_TIMEOUT=10000;
- public static final int READ_TIMEOUT=15000;
- HttpURLConnection conn;
- URL url = null;
- public JSONParser() { }
- public JSONObject makeHttpRequest(String strurl,String... params)
- {
- try
- {
- url = new URL(strurl);
- conn = (HttpURLConnection)url.openConnection();
- conn.setReadTimeout(READ_TIMEOUT);
- conn.setConnectTimeout(CONNECTION_TIMEOUT);
- conn.setRequestMethod("POST");
- conn.setDoInput(true);
- conn.setDoOutput(true);
- Uri.Builder builder = new Uri.Builder()
- .appendQueryParameter("username", params[0])
- .appendQueryParameter("password", params[1]);
- String query = builder.build().getEncodedQuery();
- OutputStream os = conn.getOutputStream();
- BufferedWriter writer = new BufferedWriter(
- new OutputStreamWriter(os, "UTF-8"));
- writer.write(query);
- writer.flush();
- writer.close();
- os.close();
- conn.connect();
- }
- catch (UnsupportedEncodingException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- try
- {
- int response_code = conn.getResponseCode();
- // Check if successful connection made
- if (response_code == HttpURLConnection.HTTP_OK)
- {
- // Read data sent from server
- InputStream input = conn.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(input));
- StringBuilder result = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null)
- {
- result.append(line);
- }
- // Pass data to onPostExecute method
- //return(result.toString());
- json = result.toString();
- }
- }
- catch (Exception e)
- {
- Log.e("Buffer Error", "Error converting result " + e.toString());
- }
- // try parse the string to a JSON object
- try
- {
- jObj = new JSONObject(json);
- }
- catch (JSONException e)
- {
- Log.e("JSON Parser", "Error parsing data " + e.toString());
- }
- // return JSON String
- return jObj;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement