Android uses httpPost to send requests to the server
- 2020-12-05 17:22:49
- OfStack
This article example shows how Android uses httpPost to send requests to the server. To share for your reference, the details are as follows:
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class RequestByHttpPost {
public static String TIME_OUT = " Operation timed out ";
public static String doPost(List<NameValuePair> params,String url) throws Exception{
String result = null;
// new HttpPost object
HttpPost httpPost = new HttpPost(url);
// Set the character set
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// Set parameter entity
httpPost.setEntity(entity);
// To obtain HttpClient object
HttpClient httpClient = new DefaultHttpClient();
// Connection timeout
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
// The request timeout
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
try {
// To obtain HttpResponse The instance
HttpResponse httpResp = httpClient.execute(httpPost);
// The judgment is that the request succeeded
if (httpResp.getStatusLine().getStatusCode() == 200) {
// Gets the returned data
result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i("HttpPost", "HttpPost Method the request is successful, and the data returned is as follows: ");
Log.i("result", result);
} else {
Log.i("HttpPost", "HttpPost Mode request failed ");
}
} catch (ConnectTimeoutException e){
result = TIME_OUT;
}
return result;
}
}
A complete class that can be used directly.
I hope this article has been helpful in Android programming.