SoFunction
Updated on 2025-03-01

Instance code for sending GET and POST requests through httpClient under Android


       public class HttpUtil {

    public static String sendDataByHttpClientGet(String path,String name,String pass){
        String result = "";
//1. Get a browser
        HttpClient client = new DefaultHttpClient();
//2. Prepare the requested address
        try {
            String arg1 = (name, "utf-8");
            String arg2 = (pass, "utf-8");
            HttpGet httpGet = new HttpGet(path+"?name="+arg1+"&pass="+arg2);

//3.Click Enter to send a request
            HttpResponse resp = (httpGet);
//Status code
            int code = ().getStatusCode();
            if(code==200){
                //().getContent();
                result = ((),"utf-8");
            }
        } catch (Exception e) {
            ();
        }
        return result;
    }

    public static String sendDataByHttpClientPost(String path,String name,String pass){
        String result = "";
//1 Get a browser
        HttpClient client = new DefaultHttpClient();

//2. Prepare the data type to be requested
        HttpPost httpPost = new HttpPost(path);
        try {
//Key-value pair NameValuePair
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            (new BasicNameValuePair("name",name));
            (new BasicNameValuePair("pass", pass));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
//3. Set POST request data entity
            (entity);
//4. Send data to the server
            HttpResponse resp = (httpPost);
            int code = ().getStatusCode();
            if(code==200){
                result = ((),"utf-8");
            }
        } catch (Exception e) {
        }
        return result;
    }

}