日期:2014-05-18 浏览次数:20869 次
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
..........
..........
..........
public static void doPost(String httpURL, List<NameValuePair> params) throws IOException{
//生成一个post请求对象
HttpPost httpPost = new HttpPost(httpURL);
HttpParams httpParams = new BasicHttpParams();
//设置超时30秒
HttpConnectionParams.setConnectionTimeout(httpParams, 10*3000);
HttpConnectionParams.setSoTimeout(httpParams, 10*3000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
//设置头信息
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context)
throws HttpException, IOException {
if(!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
//对参数进行编码
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
//操作状态
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
System.out.println("success>>>>"+ EntityUtils.toString(httpResponse.getEntity()));
}else{
System.out.println("error>>>>>>>"+ httpResponse.getStatusLine().toString());
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
&n