/**
* 发送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工具类的更多相关文章

  1. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  2. Android—关于自定义对话框的工具类

    开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...

  3. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

  4. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

  5. Guava库介绍之实用工具类

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

  6. Java程序员的日常—— Arrays工具类的使用

    这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...

  7. .net使用正则表达式校验、匹配字符工具类

    开发程序离不开数据的校验,这里整理了一些数据的校验.匹配的方法: /// <summary> /// 字符(串)验证.匹配工具类 /// </summary> public c ...

  8. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  9. JAVA 日期格式工具类DateUtil.java

    DateUtil.java package pers.kangxu.datautils.utils; import java.text.SimpleDateFormat; import java.ut ...

  10. 安卓---Toast工具类,有点懒

    package com.liunan.myfirstapp.util; import android.content.Context; import android.widget.Toast; /** ...

随机推荐

  1. restful restAPI 的定义方式

    今天听了一些rest 的讲解,感谢玖遥老大教导,晚上把整理出来,帮助那些和我一样有过迷茫的人! 我举的例子是经过我的老大讲解,以及观看阮一峰的restful架构的一些整合,和自己的拙劣见解. 首先:每 ...

  2. cuda事件的使用

    cudaEvent_t start,stop; cudaEventCreate(&start);//创建事件 cudaEventCreate(&stop); cudaEventReco ...

  3. 日新进用户200W+,解密《龙之谷》手游背后的压测故事

    2017年3月,腾讯正式于全平台上线了<龙之谷>手游,次日冲到了App Store畅销排行第二的位置,并维持到了现在.上线当日百度指数超过40万,微信游戏平台数据显示预约数780多万,而据 ...

  4. Cassandra-java操作——基本操作

    接着上篇博客,我们来谈谈java操作cassandra; 上篇博客的环境:jdk1.7 + python2.7.10 + cassandra2.2.8; 由于2.2.8没有对应的驱动文档,那么我们就用 ...

  5. dos中进入其他盘中的方法

    1.在dos中进入其他盘中直接-->e: 即可,若是进入文件夹中-->cd aaa\bbb 即可. 2.返回上级目录:-->cd..

  6. 解决win10 关键错误开始菜单和cortana无法工作 的问题(转-真的成功了)

    问题描述: 一次强制关机后出现了这个对话框,注销.重启均无法解决问题 解决过程[因为我用的英文版操作系统,所以截图都是英文,请大家自行对照自己的操作系统]: 1.ctrl+alt+del 打开任务管理 ...

  7. 认识J2SE

    1. J2SE的定义 J2SE:全称为Java 2 Standard Edition.Java 2平台包括:标准版(J2SE).企业版(J2EE)和微缩版(J2ME)三个版本. J2SE主要包括UI. ...

  8. 初步认识Thymeleaf:简单表达式和标签。(一)

    本文只适用于不会Java对HTML语言有基础的程序员们,是浏览了各大博客后收集整理,重新编辑的一篇文章,希望能对大家有所帮助. 对于Thymeleaf,网上特别官方的解释无非就是:网站或者独立应用程序 ...

  9. linuxCentOs6前期简单且必要的设置

    1.修改主机名 Sudo vi /etc/sysconfig/network(需要重启) Hostname master (不需要重启,设置当前主机名为master) Hostname查看当前主机名 ...

  10. 6、CC2541修改按键调节广播发送功率例程为持续发送4DB的蓝牙基站

    一.目的 在 OSAL操作系统-实验31 从机广播功率修改-(20141029更新).zip 基础上进行修改,该工程是通过5向按键的上下按键来控制广播功率的加减,总共有4个档位.我们的目的是直接用最高 ...