博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient post封装
阅读量:6515 次
发布时间:2019-06-24

本文共 2338 字,大约阅读时间需要 7 分钟。

/**

* @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

你可能感兴趣的文章
<Struts>ActionContext和ServletActionContext小结
查看>>
HTML5会带来一场Web革命!
查看>>
使用纯代码的界面程序
查看>>
[数读]从开户数看这一波牛市
查看>>
MVP模式简单使用小记
查看>>
DB2 查看当前连接的Application ID
查看>>
ELK6.2.2(elasticsearch+logstash+kibana)开源日志分析平台搭建(三):logstash简单收集...
查看>>
HTTPS原理
查看>>
Object-c 常用细节
查看>>
4、索引 文档 类型 映射 _id
查看>>
Linux top 命令详解
查看>>
实现滚动单选控件
查看>>
白用功...详情这几天继续写
查看>>
spring使用注解@value取properties时无法取到值
查看>>
如何在Java中实现线程间通信
查看>>
算法初级(冒泡,插入,快速,选择)
查看>>
Sql 一次性插入多条记录
查看>>
Action Pascal(A语言)v3.0官方版
查看>>
实操 Web Cache (第二版)
查看>>
颠覆你对区块链的认识
查看>>