The instance code for GET and POST requests is sent via httpClient under Android
- 2020-05-17 06:25:10
- OfStack
public class HttpUtil {
public static String sendDataByHttpClientGet(String path,String name,String pass){
String result = "";
//1. Access to the 1 A browser
HttpClient client = new DefaultHttpClient();
//2. Prepare the requested address
try {
String arg1 = URLEncoder.encode(name, "utf-8");
String arg2 = URLEncoder.encode(pass, "utf-8");
HttpGet httpGet = new HttpGet(path+"?name="+arg1+"&pass="+arg2);
//3. Press enter to request
HttpResponse resp = client.execute(httpGet);
// Status code
int code = resp.getStatusLine().getStatusCode();
if(code==200){
//resp.getEntity().getContent();
result = EntityUtils.toString(resp.getEntity(),"utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String sendDataByHttpClientPost(String path,String name,String pass){
String result = "";
//1 Access to the 1 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>();
params.add(new BasicNameValuePair("name",name));
params.add(new BasicNameValuePair("pass", pass));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
//3. Set up the POST Request data entity
httpPost.setEntity(entity);
//4. Send data to the server
HttpResponse resp = client.execute(httpPost);
int code = resp.getStatusLine().getStatusCode();
if(code==200){
result = EntityUtils.toString(resp.getEntity(),"utf-8");
}
} catch (Exception e) {
}
return result;
}
}