SoFunction
Updated on 2025-04-11

Methods for using Post requests in Android

This article describes the method of using Post request in Android. Share it for your reference. The details are as follows:

1. Required scenarios

You can easily initiate a post request using $.post() in jQuery. Sometimes you have to get some data from the server in android programs, so you have to use post requests.

2. The main categories that need to be used

The main classes used to use post requests in android are HttpPost, HttpResponse, EntityUtils

3. Main ideas

1. Create an HttpPost instance and set the URL that needs to request the server.

2. Set parameters for the created HttpPost instance. When setting parameters, use the NameValuePair class using key-value pairs.

3. Initiate a post request to get the return instance HttpResponse

4. Use EntityUtils to process the returned value entity (can obtain the returned string or the returned byte array)

The code is relatively simple, and the comments are added, so I posted it directly

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class HttpURLActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    ("start url...");
    String url = "http://192.168.2.112:8080/JustsyApp/Applet";
    // The first step is to create an HttpPost object    HttpPost httpPost = new HttpPost(url);
    // Setting HTTP POST request parameters must use NameValuePair object    List<NameValuePair> params = new ArrayList<NameValuePair>();
    (new BasicNameValuePair("action", "downloadAndroidApp"));
    (new BasicNameValuePair("packageId", "89dcb664-50a7-4bf2-aeed-49c08af6a58a"));
    (new BasicNameValuePair("uuid", "test_ok1"));
    HttpResponse httpResponse = null;
    try {
      // Set httpPost request parameters      (new UrlEncodedFormEntity(params, HTTP.UTF_8));
      httpResponse = new DefaultHttpClient().execute(httpPost);
      //(().getStatusCode());
      if (().getStatusCode() == 200) {
        // The third step is to live with the getEntity method and return the result        String result = (());
        ("result:" + result);
        (, "result:" + result);
      }
    } catch (ClientProtocolException e) {
      ();
    } catch (IOException e) {
      ();
    }
    ("end url...");
    setContentView();
  }
}

ADD: Use HttpURLConnection to make post request:

String path = "http://192.168.2.115:8080/android-web-server/?PackageID=89dcb664-50a7-4bf2-aeed-49c08af6a58a";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) ();
("POST");
(5000);
(());

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