Wednesday, 10 December 2014

JSON Pars get response pass parameter string

Pass Parameter in String (BaseNameValue Class )

try
{

                        HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url");
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user", semail)); 
nameValuePairs.add(new BasicNameValuePair("pass",spass));  
nameValuePairs.add(new BasicNameValuePair("os_type",spass));  
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String originalResponse = EntityUtils.toString(response.getEntity());


}
catch(Exception e)
{
}






//Json Pars Post Method by Sending Json

public static String postRequest(String url, String json) {

String result = "";
Log.e("Data","Url " + url + " Data is " + json.toString());

try {


HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String orignalResponse = reader.readLine();
JSONTokener tokener = new JSONTokener(orignalResponse);

JSONObject jsonOBJ = new JSONObject(tokener);


Log.e("Json ", "Json: "+jsonOBJ.toString());
if (jsonOBJ != null)
{
result = jsonOBJ.toString();
result = result.trim();
}
}
catch (Exception e)
{
e.printStackTrace();
Log.e("Exception ", e.getMessage());

}
return result;
}



//Json Pars Get Method by Sending Json 

public static String getRequest(String url) {

String result = "";
Log.e("Data","Url " + url );

try {


HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
HttpGet get = new HttpGet(url);
// StringEntity se = new StringEntity(json.toString());
// se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// post.setEntity(se);
response = client.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String orignalResponse = reader.readLine();
JSONTokener tokener = new JSONTokener(orignalResponse);

JSONObject jsonOBJ = new JSONObject(tokener);


Log.e("Json ", "Json: "+jsonOBJ.toString());
if (jsonOBJ != null)
{
result = jsonOBJ.toString();
result = result.trim();
}
}
catch (Exception e)
{
e.printStackTrace();
Log.e("Exception ", e.getMessage());

}
return result;
}


How to call



String response = Utility.postRequest(Comman.URL, json.toString());
JSONObject jObject = new JSONObject(response);

No comments:

Post a Comment