For posting data to web service in Android we can use HTTP POST in Android. Please see the class below that will post some data to a web service and and get the result JSON. This is done using async task of Android.
public class HttpHelper extends AsyncTask < Void, Void, String >
{
private String url = "SOME_POST_URL";
@Override
protected String doInBackground(Void...params)
{
String resultString = null;
JSONObject json = new JSONObject();
try
{
json.put("email", "EMAIL");
json.put("password", "PASSWORD");
}
catch (JSONException e)
{}
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
ByteArrayEntity arrayEntity = new ByteArrayEntity(json.toString().getBytes());
httpPost.setEntity(arrayEntity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse;
try
{
httpResponse = client.execute(httpPost);
InputStream stream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null)
{
Log.e("Line===", line);
buffer.append(line);
}
resultString = buffer.toString();
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultString;
}
@Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
//result will contains the response JSON
}
}
Here on the onPostExecute method we will get the resultant JSON in result variable.
