Call a Web service from android

package com.example.root.myapplication;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.os.AsyncTask;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {

protected void onCreate(Bundle savedInstanceState) {
Button btnhitapi=(Button) findViewById(;
btnhitapi.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new HttpRequestTask().execute();

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == {
return true;

return super.onOptionsItemSelected(item);

private class HttpRequestTask extends AsyncTask {
protected Greeting doInBackground(Void… params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(“”);
//post.setHeader(“content-type”, “application/json”);

List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair(“username”, “uma”));
nameValuePairs.add(new BasicNameValuePair(“password”, “Hi”));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());

Log.i(“Response”, respStr.toString());
Greeting greeting=new Greeting();
return greeting;

} catch (Exception e) {
Log.e(“MainActivity”, e.getMessage(), e);

return null;

protected void onPostExecute(Greeting greeting) {


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *