http工具类
/**
* 发送post请求工具方法
*
* @Methods Name HttpPost
* @Create In 2014年10月28日 By wangfei
* @param url
* @param method
* @param paramMap
* @return String
*/
@SuppressWarnings("rawtypes")
public static String HttpPost(String url, String method, Map paramMap) {
// 构造HttpClient的实例
HttpClient httpClient = getHttpClient();
LOGGER.debug("url is {},method is {},paramMap is {}", new Object[] { url, method, paramMap });
String encoding = "UTF-8";
String webUrl = url + "/" + method;
if (encoding == null || "".equals(encoding))
encoding = "UTF-8";
StringBuffer sBuffer = new StringBuffer();
// httpClient.set
// 创建POS方法的实例
NameValuePair[] pairs = null;
List<NameValuePair> list = new ArrayList<NameValuePair>();
PostMethod postMethod = new PostMethod(webUrl);
if (paramMap != null) {
pairs = new NameValuePair[paramMap.size()];
Set set = paramMap.keySet();
Iterator it = set.iterator();
int i = 0;
while (it.hasNext()) {
Object key = it.next();
Object value = paramMap.get(key);
if (!HttpUtil.checkNull(value)) {
pairs[i] = new NameValuePair(key.toString(), value.toString());
list.add(pairs[i]);
}
i++;
}
postMethod.setRequestBody(list.toArray(new NameValuePair[0]));
}
postMethod.setRequestHeader("Connection", "close");
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
try {
// 执行getMethod
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
LOGGER.error("statusCode is {},paramMap is {}", new Object[] { statusCode, paramMap });
System.err.println("Method failed: " + postMethod.getStatusLine());
sBuffer = new StringBuffer();
} else {
sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + "");
}
} catch (Exception e) {
LOGGER.error("paras is {},exception is {}", new Object[] { paramMap, e });
} finally {
// 释放连接
postMethod.releaseConnection();
}
String res = sBuffer.toString();
LOGGER.debug("url is {},method is {},paramMap is {},res is {}", new Object[] { url, method, paramMap, res });
return res;
}
/**
* 发送Get请求工具方法
*
* @Methods Name HttpGet
* @Create In Dec 30, 2014 By lihongfei
* @param url
* @param method
* @param paramMap
* @return String
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String HttpGet(String url, String method, Map paramMap) {
LOGGER.debug("HttpGet url is {},method is {},paramMap is {}", new Object[] { url, method, paramMap });
// 设置编码格式
HttpClient httpClient = getHttpClient();
String encoding = "GBK";
String webUrl = url + "/" + method;
if (encoding == null || "".equals(encoding))
encoding = "GBK";
String queryString = createLinkString(paramMap);
webUrl = webUrl + "?" + queryString;
StringBuffer sBuffer = new StringBuffer();
// 构造HttpClient的实例
GetMethod gettMethod = null;
// httpClient.set
try {
URI uri = new URI(webUrl, false, encoding);
gettMethod = new GetMethod(uri.toString());
gettMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
gettMethod.setRequestHeader("Connection", "close");
// 执行getMethod
int statusCode = httpClient.executeMethod(gettMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + gettMethod.getStatusLine());
sBuffer = new StringBuffer();
} else {
sBuffer = new StringBuffer(gettMethod.getResponseBodyAsString() + "");
}
} catch (Exception e) {
} finally {
if(gettMethod != null){
// 释放连接
gettMethod.releaseConnection();
}
}
String res = sBuffer.toString();
LOGGER.debug("url is {},method is {},paramMap is {},response is {}",
new Object[] { url, method, paramMap, res });
return res;
}
/**
* 发送Get请求工具方法,处理参数有中文字符
*
* @Methods Name HttpGet
* @Create In Dec 30, 2014 By songw
* @param url
* @param method
* @param paramMap
* @return String
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String HttpGetByUtf(String url, String method, Map paramMap) {
// 设置编码格式
String encoding = "UTF-8";
String webUrl = url + "/" + method;
if (encoding == null || "".equals(encoding))
encoding = "UTF-8";
String queryString = createLinkString(paramMap);
webUrl = webUrl + "?" + queryString;
StringBuffer sBuffer = new StringBuffer();
HttpClient httpClient = new HttpClient();
GetMethod gettMethod = null;
// httpClient.set
try {
URI uri = new URI(webUrl, false, encoding);
gettMethod = new GetMethod(uri.toString());
gettMethod.setRequestHeader("Connection", "close");
gettMethod.setRequestHeader("Content-type", "text/html;charset=utf-8");
gettMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); // 连接5秒超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);// 读取30秒超时
// 执行getMethod
int statusCode = httpClient.executeMethod(gettMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + gettMethod.getStatusLine());
sBuffer = new StringBuffer();
} else {
sBuffer = new StringBuffer(gettMethod.getResponseBodyAsString() + "");
}
} catch (Exception e) {
LOGGER.error("HttpGetByUtf url is {},method is {},paramMap is {},exception is {}",
new Object[] { url, method, paramMap, e.getMessage() });
} finally {
if(gettMethod != null){
// 释放连接
gettMethod.releaseConnection();
}
}
String res = sBuffer.toString();
LOGGER.debug("url is {},method is {},paramMap is {},response is {}",
new Object[] { url, method, paramMap, res });
return res;
}
/**
* 发送Get请求工具方法,处理参数有中文字符
*
* @Methods Name HttpGet
* @Create In Dec 30, 2014 By songw
* @param url
* @param method
* @param paramMap
* @return String
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String HttpGetByUtfNoMenthod(String url, String method, Map paramMap) {
// 设置编码格式
String encoding = "UTF-8";
String webUrl = url + "/" + method;
if (StringUtils.isEmpty(method)) {
webUrl = url;
}
if (encoding == null || "".equals(encoding))
encoding = "UTF-8";
String queryString = createLinkString(paramMap);
webUrl = webUrl + "?" + queryString;
StringBuffer sBuffer = new StringBuffer();
HttpClient httpClient = new HttpClient();
GetMethod gettMethod = null;
// httpClient.set
try {
URI uri = new URI(webUrl, false, encoding);
gettMethod = new GetMethod(uri.toString());
gettMethod.setRequestHeader("Connection", "close");
gettMethod.setRequestHeader("Content-type", "text/html;charset=utf-8");
gettMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); // 连接5秒超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);// 读取30秒超时
// 执行getMethod
int statusCode = httpClient.executeMethod(gettMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + gettMethod.getStatusLine());
sBuffer = new StringBuffer();
} else {
sBuffer = new StringBuffer(gettMethod.getResponseBodyAsString() + "");
}
} catch (Exception e) {
LOGGER.error("HttpGetByUtf url is {},method is {},paramMap is {},exception is {}",
new Object[] { url, method, paramMap, e.getMessage() });
} finally {
if(gettMethod != null){
// 释放连接
gettMethod.releaseConnection();
}
}
String res = sBuffer.toString();
LOGGER.debug("url is {},method is {},paramMap is {},response is {}",
new Object[] { url, method, paramMap, res });
return res;
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url
* 请求的URL地址
* @param params
* 请求的查询参数,可以为null
* @return 返回请求响应的HTML
*/
@SuppressWarnings("deprecation")
public static String doPost(String url, String json) {
LOGGER.debug("doPost url is {},parajson is {}", new Object[] { url, json });
String response = null;
PostMethod method = new PostMethod(url);
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
// 设置Http Post数据
try {
method.setRequestBody(json);
method.setRequestHeader("Connection", "close");
method.setRequestHeader("Content-type", "application/json");
HttpClient httpClientNew = new HttpClient();
httpClientNew.getHttpConnectionManager().getParams().setConnectionTimeout(50000); // 连接5秒超时
httpClientNew.getHttpConnectionManager().getParams().setSoTimeout(70000);// 读取30秒超时
httpClientNew.executeMethod(method);
// if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
// }
} catch (Exception e) {
LOGGER.error("url is {},parajson is {},Exception is {}", new Object[] { url, json, e.getMessage() });
} finally {
method.releaseConnection();
}
LOGGER.debug("url is {},parajsonjson is {},response is {}", new Object[] { url, json, response });
return response;
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
*
* @param params
* 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
public static boolean checkNull(Object target) {
if (target == null || "".equals(target.toString().trim())
|| "null".equalsIgnoreCase(target.toString().trim())) {
return true;
}
return false;
}
public static HttpClient getHttpClient() {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(50000); // 连接5秒超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(70000);// 读取30秒超时
return httpClient;
}
http工具类的更多相关文章
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Android—关于自定义对话框的工具类
开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...
- [转]Java常用工具类集合
转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...
- js常用工具类.
一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...
- Guava库介绍之实用工具类
作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...
- Java程序员的日常—— Arrays工具类的使用
这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...
- .net使用正则表达式校验、匹配字符工具类
开发程序离不开数据的校验,这里整理了一些数据的校验.匹配的方法: /// <summary> /// 字符(串)验证.匹配工具类 /// </summary> public c ...
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- JAVA 日期格式工具类DateUtil.java
DateUtil.java package pers.kangxu.datautils.utils; import java.text.SimpleDateFormat; import java.ut ...
- 安卓---Toast工具类,有点懒
package com.liunan.myfirstapp.util; import android.content.Context; import android.widget.Toast; /** ...
随机推荐
- 樱花的季节,教大家用canvas画出飞舞的樱花树
又到了樱花的季节,教大家使用canvas画出飞舞的樱花树效果. 废话少说,先看效果. 演示效果地址:http://suohb.com/work/tree4.htm 查看演示效果 第一步,我们先画出一棵 ...
- maridb安装审计audit插件
1.下载插件 https://mariadb.com/kb/en/mariadb-audit- plugin/ 比较新的mariadb版本audit插件直接内嵌在版本里,可以直接安装 INSTALL ...
- pyqt样式表语法笔记(中)--原创
pyqt样式表语法笔记(中) pyqt QSS python 样式表 一.弹窗 在日常的各种桌面软件的使用中,我们都会碰到弹窗.例如注册,登录的时候,会有相应的信息弹窗,这里就以信息收集弹窗为例进行弹 ...
- 如何使用bootstrap
前言: 前几天,本想做一个登陆界面,但自己写form表单必然很丑,所以想用下bootstarp框架,之前听别人说bootstrap很牛的样子.但我完全不会bootstrap... 下载&目录 ...
- JavaScript如何一次性展示几万条数据
有一位同事跟大家说他在网上看到一道面试题:“如果后台传给前端几万条数据,前端怎么渲染到页面上?”,如何回答? 于是办公室沸腾了, 同事们讨论开了, 你一言我一语说出自己的方案. 有的说直接循环遍历生成 ...
- Windows运行命令大全
inetmgr 启动IIS控制台winver 检查Windows版本 wmimgmt.msc 打开Windows管理体系结构(wmi) wupdmgr Windows更新程序 wscript Wi ...
- Excel图表-创意雷达图-原创图表
p{ font-size: 15px; } .alexrootdiv>div{ background: #eeeeee; border: 1px solid #aaa; width: 99%; ...
- 老李分享:接电话之uiautomator 2
case解释 首先要了解进入uiwatcher方法中的机制,是在你某个控件找不到的情况下会进入.但是你得保证进入以后处理完来电界面以后,这条case得保证正确,那么说明回来以后这个控件要能找到.刚开始 ...
- codevs2019 Uva10029 递变阶梯
提交地址:[codevs][Uva] 题目描述 递变是指通过增加.减少或改变单词x中的一个字母,使它变成字典中的另一个单词y.比如将dig变成dog,将dog变成do都是递变.递变阶梯是一个按字典序 ...
- webx request注入单例增强实现
由于在spring中request对象的scope限制导致了request对象无法直接注入到单例bean中,所以webx对其进行了增强实现,达到单例注入的目的. 实现原理大致如下: 1 启动时注册全局 ...