作者:SH_ZTH_611_666_104_534 | 来源:互联网 | 2023-01-13 18:38
版本:4.1带参数名的情况HttpClienthttpClientnewDefaultHttpClient();HttpPosthttpPostnewHttpPo
版本:4.1
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);// httpPost.setHeader("Accept-Encoding", "gzip,deflate");//表示返回的数据是压缩的zip格式
String postParam = "";//请求的参数内容
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("data", postParam));
httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200) {if (entity.getContentEncoding().toString().equalsIgnoreCase("Content-Encoding: gzip")) {
response.setEntity(new GzipDecompressingEntity(response.getEntity())); //对zip进行解压
entity = response.getEntity();
}
String responseContent = EntityUtils.toString(entity);
System.out.println("responseContent: \n" + responseContent);
}
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// httpPost.setHeader("Accept-Encoding", "gzip,deflate");//表示返回的数据是压缩的zip格式
String postParam = "";//请求的参数内容
StringEntity paramEntity = new StringEntity(postParam);//无参数名,只是参数内容
httpPost.setEntity(paramEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200) {if (entity.getContentEncoding().toString().equalsIgnoreCase("Content-Encoding: gzip")) {
response.setEntity(new GzipDecompressingEntity(response.getEntity())); //对zip进行解压
entity = response.getEntity();
}
String responseContent = EntityUtils.toString(entity);
System.out.println("responseContent: \n" + responseContent);
}
}
Httpclient并发处理处理:主要改变Httpclient对象的生成
/**
* 适合多线程的HttpClient,用httpClient4.2.1实现
* @return DefaultHttpClient
*/
public static DefaultHttpClient getHttpClient()
{
// 设置组件参数, HTTP协议的版本,1.1/1.0/0.9
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
//设置连接超时时间
int REQUEST_TIMEOUT = 60*1000; //设置请求超时60秒钟
int SO_TIMEOUT = 60*1000; //设置等待数据超时时间60秒钟
//HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
//HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
//设置访问协议
SchemeRegistry schreg = new SchemeRegistry();
schreg.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
schreg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
//多连接的线程安全的管理器
PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schreg);
pccm.setDefaultMaxPerRoute(20); //每个主机的最大并行链接数
pccm.setMaxTotal(100); //客户端总并行链接最大数
DefaultHttpClient httpClient = new DefaultHttpClient(pccm, params);
return httpClient;
}