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; /** ...
随机推荐
- 新手向:Java基础知识
Java 接口 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明.一个类通过继承接口的方式,从而来继承接口的抽象方法. 接口并 ...
- 《用Python做HTTP接口测试》学习感悟
机缘巧合之下,报名参加了阿奎老师发布在"好班长"的课程<用Python做HTTP接口测试>,报名费:15rmb,不到一杯咖啡钱,目前为止的状态:坚定不移的跟下去,自学+ ...
- 移动web页面支持弹性滚动的3个方案
有段时间一直折腾移动端页面弹性滚动的各种问题,做了点研究,今天做个小分享~ 传统 pc 端中,子容器高度超出父容器高度,通常使用 overflow:auto 可出现滚动条拖动显示溢出的内容,而移动we ...
- Linux之cut命令
cut 参数: -d 指定分隔符,与-f 一起使用,默认是空格.例如:-d“|” -f 指定取第几段的数据与-d一起使用 -c 以字符为单位取出固定字符区间 示例: 取不连续区间的内容的时候使用 ...
- 【react-router】从Link组件和a标签的区别说起,react-router如何实现导航并优化DOM性能?
(注:参考自官方英文文档V3.X版本) react-router是伴随着react框架出现的路由系统,它也是公认的一种优秀的路由解决方案.在使用react-router时候,我们常常会使用其自带的路径 ...
- 创建keystone的catalog时提示:‘Internal Server Error (HTTP 500)’
在生成keystone的catalog时: [root@controller ~]# openstack service create --name keystone --description &q ...
- IOS开发创建开发证书及发布App应用(八)——使用Application Loader工具上传应用
8.使用Application Loader工具上传应用 继续第七步在iTunes所创建的应用,打开应用,如下图 点击详情按钮进去之后,单击右上角Ready to Upload Binary按钮,如下 ...
- 将ROS中的/sensor_msgs/NavSatFix数据导入google earth显示轨迹
将ros中的gps_msg数据导入google earth显示轨迹 [TOC] 1. 获取GPS数据 将ros中发布的gps topic输出到文本中 rostopic echo -p /gpsData ...
- 老李谈HTTP1.1的长连接 1
老李谈HTTP1.1的长连接 poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣,请大家咨询qq:9088214 ...
- 4.在浏览器中解析XML
要在浏览器中解析获取XML数据,一般只需经过两个步骤:第一,将XML文档.XML字符串转化成XMLDoc对象.第二,使用JS操作XMLDoc对象. 3.1 将XML文档或XML字符串转化成XMLDoc ...