HttpClient post封装

本文介绍了一个用于封装HTTP Post请求的实用工具类HttpUtils。该工具类提供了设置连接超时时间、最大连接数等参数的功能,并实现了Post请求的发送及响应结果的处理。通过示例演示了如何使用此工具类进行Post请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
* @title HttpUtils
* @description post请求封装
* @author maohuidong
* @date 2017-12-18
*/
public static class HttpUtils {


/**
* 定义编码格式 UTF-8
*/
public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";


private static final String EMPTY = "";

private static MultiThreadedHttpConnectionManager connectionManager = null;

private static int connectionTimeOut = 25000;

private static int socketTimeOut = 25000;

private static int maxConnectionPerHost = 20;

private static int maxTotalConnections = 20;

private static HttpClient client;

static{
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
connectionManager.getParams().setSoTimeout(socketTimeOut);
connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
client = new HttpClient(connectionManager);
}

/**
* @function URLPost
* @param
* @description Post请求
* @return 请求后的结果
* @author maohuidong
* @date 2017-12-18
*/
public static String URLPost(String url, Map<String, String> params, String enc) throws UnsupportedEncodingException{
String response = EMPTY;
PostMethod postMethod = null;
try {
postMethod = new PostMethod(url);
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + enc);

//将表单的值放入postMethod中
Set<String> keySet = params.keySet();
for(String key : keySet){
String value = params.get(key);
postMethod.addParameter(key, value);
}
//执行postMethod
int statusCode = client.executeMethod(postMethod);
if(statusCode == HttpStatus.SC_OK) {
response = postMethod.getResponseBodyAsString();
System.out.println(postMethod.getResponseCharSet());
}
}catch(HttpException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(postMethod != null){
postMethod.releaseConnection();
postMethod = null;
}
}
return response;
}
}

 

Test:

Map<String, String> map = new HashMap<String, String>();
map.put("token", token);
map.put("type", type);

String result = HttpUtils.URLPost("http://localhost:8080/web_user_xxhzx/check_findUserInfo.action", map, "UTF-8");

 

notice:

如果返回乱码,需要转码:

result = new  String(result.getBytes("ISO-8859-1"),"UTF-8");

返回的编码可以通过postMethod.getResponseCharSet()获取到

转载于:https://www.cnblogs.com/maohuidong/p/8056121.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值