public class HttpClientRequest {
private final static String ENCOD = "UTF-8";
private final static int timeout = 3000;
public String request(String request, List<NameValuePair> pairs) {
HttpClient client = new DefaultHttpClient();
// 设置连接超时
HttpConnectionParams.setConnectionTimeout(client.getParams(), timeout);
HttpConnectionParams.setSoTimeout(client.getParams(), timeout);
HttpPost httpPost = new HttpPost(request);
// 检测参数
for (NameValuePair pair : pairs) {
if (pair.getName() == null || pair.getName().equals("")) {
throw new IllegalArgumentException("参数名称不能为空!");
}
if (pair.getValue() == null) {
throw new NullPointerException("参数值不能为空!");
}
}
UrlEncodedFormEntity formEntity;
try {
// 请求
formEntity = new UrlEncodedFormEntity(pairs, ENCOD);
httpPost.setEntity(formEntity);
// 响应
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, ENCOD);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return null;
}
}
HttpClient 4.x使用实例
最新推荐文章于 2021-02-13 04:58:55 发布