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; /** ...
随机推荐
- (2)java中的集中关系,is a, has a, 继承,重点聊聊继承
java中常见的类关系(javacore上面也有介绍道的) 1.is a关系() 2.has a 整体与局部的关系 3.继承关系 是现实世界中存在而上面两种关系又无法描述的 当然谈的最多的是继承关系, ...
- 关于Tarjan(3)——离线LCA
LCA(最近公共祖先),指对于一棵树上任意两个节点往上走最早都能到达的节点. 求LCA有两种方法,一种是倍增,另一种则是Tarjan........ Tarjan巧妙利用并查集的思想: 这里的Tarj ...
- Java中元组的使用
元组在计算机领域有着特殊的意义,这个名字听起来似乎有些陌生, 平时在写代码也基本没什么应用场景, 然而, 出人意料的是, 元组跟程序设计密切相关, 可能有的同学不知道, 关系数据库中的「纪录」的另一个 ...
- WebStorm里启动electron项目
WebStorm里启动electron项目,其实很简单 一.第一步打开下面的窗口 二.然后输入electron .,然后敲下 回车键,然后等会项目界面就会出现了. PS:electron 和 点之间有 ...
- 老李推荐: 第1章1节《MonkeyRunner源码剖析》概述:前言
老李推荐: 第1章1节<MonkeyRunner源码剖析>概述:前言 前言 相信大家做过安卓移动平台UI自动化开发的必然会用过,至少听过MonkeyRunner这个名字.MonkeyR ...
- 使用 SLF4J + LogBack 构建日志系统(转)
转载自:http://www.cnblogs.com/mailingfeng/p/3499436.html 上次我们讨论了如何选择一个好的开源日志系统方案,其中的结论是:使用 SLF4J + LogB ...
- 奇葩问题:同样的字符串equal为false
问题:什么情况下 "同样" 的字符串会不equal呢?例如 "a".equal("a") => false 在你看来,这可能是个 ...
- JavaScript学习总结(一)DOM文档对象模型
一.文档(D) 一个网页运行在浏览器中,他就是一个文档对象. 二.对象(O) "对象"是一种自足的数据集合.与某个特定对象相关联的变量被称为这个对象的属性,只能通过某个对象调用的函 ...
- python 面向对象编程(二)
在上一篇文章中谈到了类的基本定义和使用方法,这只体现了面向对象编程的三大特点之一:封装. 下面就来了解一下另外两大特征:继承和多态. 在Python中,如果需要的话,可以让一个类去继承一个类,被继承的 ...
- AES算法,DES算法,RSA算法JAVA实现
1 AES算法 1.1 算法描述 1.1.1 设计思想 Rijndael密码的设计力求满足以下3条标准: ① 抵抗所有已知的攻击. ② 在多个平台上速度快,编码紧凑. ③ 设计 ...