Here i am passing json string parameter to php webservice. To consume php post method we will use HttpPost.
To create JSON String in android:
JSONObject json = new JSONObject();
json.put("name", "");
json.put("email", "");
json.put("password", "");
Log.i("json Object", json.toString());
Pass the parameter to post method:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userinfo", json.toString()));
Get the response InputStream like this:
HttpResponse response;
InputStream is = null;
response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Full Code:
HttpResponse response;
JSONObject json = new JSONObject();
String json1 = "";
JSONObject jObj = null;
InputStream is = null;
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(
"Your URL");
json.put("name", "");
json.put("email", "");
json.put("password", "");
Log.i("jason Object", json.toString());
post.setHeader("userinfo", json.toString());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userinfo", json.toString()));
post.setEntity(new UrlEncodedFormEntity(params));
response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json1 = sb.toString();
Log.i("jason Object", sb.toString());
Log.e("JSON", json1);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json1);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("final Response", jObj.toString());
Log.d("status", jObj.getString("status")); //Declare your status or message or json string variable
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse to String android
Manifest.xml:
Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>
Note:
In AVD to connect to localhost you need to use urlhttp://10.0.2.2/ instead of http://localhost/.
No comments:
Post a Comment