在Android中发送HTTP请求

I am sending HTTP request to a PHP site in a server. But while I am sending the request the phone getting stuck for a couple of seconds. Sometimes Its getting long time to send and receive the requested result.

How to solve this. Pls help me to find a solution. Thanks.

This is the code I tried...

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

}

To make http request you have to use AsyncTask.This will run in background.

see below link for reference

http://www.vogella.com/articles/AndroidPerformance/article.html

Use AsyncTask for making http request from UI thread. Change your code as:

private class LongOperation extends AsyncTask<String, Void, String> {

          @Override
          protected Void doInBackground(String... params) {

              //Call your post method here
                  postData();

                  return null;
          }      

          @Override
          protected void onPostExecute(String result) {
              // get result after operation complete
          }

          @Override
          protected void onPreExecute() {
          }

          @Override
          protected void onProgressUpdate(Void... values) {
          }
    }   

You should perform network operations in some other thread than network thread, please see handler and async task for the same.

http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask

http://developerlife.com/tutorials/?p=290

Try like this, you can use: HttpClient.exeucute(httpPost) and get the HttpResponse

This work for me perfect.

DefaultHttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    List<NameValuePair> params = new ArrayList<NameValuePair>();

    pairs.add(new BasicNameValuePair("email", stringeditemail));

    UrlEncodedFormEntity formEntity = null;
    try {
        formEntity = new UrlEncodedFormEntity(params);

    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    post.setEntity(formEntity);

    try {

        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            return iStream_to_String(is);
        } else {
            return "Hello This is status ==> :"
                    + String.valueOf(statusCode);
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;

}

And create the method for the convert the stringbuilder to string

 public static String iStream_to_String(InputStream is1) {
    BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
    String line;
    StringBuilder sb = new StringBuilder();
    try {
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String contentOfMyInputStream = sb.toString();
    return contentOfMyInputStream;
}