SoFunction
Updated on 2025-04-10

How to send requests to server using httpPost

This article describes the method of Android using httpPost to send requests to the server. Share it for your reference, as follows:

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class RequestByHttpPost {
  public static String TIME_OUT = "Operation timeout";
  public static String doPost(List<NameValuePair> params,String url) throws Exception{
    String result = null;
     // Create a new HttpPost object     HttpPost httpPost = new HttpPost(url);
     // Set character set     HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
     // Set parameter entity     (entity);
     // Get the HttpClient object     HttpClient httpClient = new DefaultHttpClient();
     //Connection timeout     ().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
     //Request timeout     ().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
     try {
       // Get the HttpResponse instance      HttpResponse httpResp = (httpPost);
      // The judgment is that the request is successful      if (().getStatusCode() == 200) {
        // Get the returned data        result = ((), "UTF-8");
        ("HttpPost", "The HttpPost method request was successful, and the data returned is as follows:");
        ("result", result);
      } else {
        ("HttpPost", "HttpPost method request failed");
      }
     } catch (ConnectTimeoutException e){
       result = TIME_OUT;
     }
     return result;
  }
}

A complete class that can be used directly.

I hope this article will be helpful to everyone's Android programming design.