网站建设
网站推广
网络推广
Network promotion
关键词SEO优化
品牌推广
两V一抖
广告媒介投放
品牌网站建设
企业网站建设
门户网站建设
网站代运营
集团网站建设
外贸网站建设
营销型网站建设
网站运营维护
案例
方案
网站方案
Solution
教育培训
商城
美容化妆品
LED
软件IT
房地产
装饰行业
节能环保
手机数码
集团上市公司
金融行业
物流
钟表
数码电器
旅游
其他
电商网站开发
电商网站开发
E-commerce & System
定制化电子商务系统
产品商城网站建设方案
移动手机电商网站解决方案
微信会员电商解决方案
系统开发
P2P金融平台
产品众筹平台
股权众筹平台
微信小程序
微信小程序
微商城
微官网
微活动
我们
我们
About Us
了解我们
关于快上网
实力认可
快上网与众不同
理念与信仰
售后支持
我们的客户
客户列表
客户评价
联系
联系
Contact Us
联系我们
业务热线:
028-86922220
邮箱:
service@cdxwcx.com
人才招聘
HR电话:
13518219792
精准传达 • 有效沟通
从品牌网站建设到网络营销策划,从策略到执行的一站式服务
网站建设
>
查看其它板块
网站建设知识
网站营销推广
网站设计观点
网站优化排名
网站商城开发
Http工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
HTTP工具类
@author ycye
*/
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static final int OSB_TIME_OUT=20;
/**
HTTPGET
@param url
@param paramsMap
@param encoding
@return
*/
public final static String httpGet(String url, Map
paramsMap, String encoding) throws Exception{
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
return get(url, paramsMap, headerMap, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSGET
@param url
@param paramsMap
@param encoding
@return
*/
public final static String httpsGet(String url, Map
paramsMap, String encoding) throws Exception{
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
return get(url, paramsMap, headerMap, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSPOST
@param url
@param paramsMap
@param encoding
@return
*/
public final static String httpPost(String url, Map
paramsMap, String encoding) {
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
// 组装参数
List
params = parseMap2BasicForm(paramsMap);
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, encoding);
} catch (UnsupportedEncodingException e) {
logger.error("httpPost fail" + e.getMessage(), e);
}
return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSPOST
@param url
@param paramsMap
@param headerMap
@param encoding
@return
*/
public final static String httpPost(String url, Map
paramsMap,Map
headerMap, String encoding) {
headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=" + encoding);
// 组装参数
List
params = parseMap2BasicForm(paramsMap);
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, encoding);
} catch (UnsupportedEncodingException e) {
logger.error("httpPost fail" + e.getMessage(), e);
}
return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSPOST
@param url
@param paramsMap
@param encoding
@return
*/
public final static String httpsPost(String url, Map
paramsMap, String encoding) {
return httpPost(url, paramsMap, encoding);
}
/**
HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
@param url
@param paramJson
@param headerMap
@param encoding
@return
*/
public final static String httpsPostJson(String url, String paramJson,Map
headerMap, String encoding) {
headerMap.put("Content-Type", "application/json; charset=" + encoding);
// 组装参数
StringEntity entity = null;
try {
logger.debug("send post data:" + paramJson);
entity = new StringEntity(paramJson, encoding);
entity.setContentType("application/x-www-form-urlencoded");
} catch (Exception e) {
logger.error("组装参数失败" + e.getMessage(), e);
}
return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
*
@param url
@param paramJson
@param headerMap
@param encoding
@return
*/
public final static HttpResponse nativeHttpsPostJson(String url, String paramJson,Map
headerMap, String encoding) {
headerMap.put("Content-Type", "application/json; charset=" + encoding);
// 组装参数
StringEntity entity = null;
try {
logger.debug("send post data:" + paramJson);
entity = new StringEntity(paramJson, encoding);
} catch (Exception e) {
logger.error("组装参数失败" + e.getMessage(), e);
}
return nativePost(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
@param url
@param paramJson
@param encoding
@return
*/
public final static String httpsPostJson(String url, String paramJson, String encoding) {
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "application/json; charset=" + encoding);
// 组装参数
StringEntity entity = null;
try {
logger.debug("send post data:" + paramJson);
entity = new StringEntity(paramJson, encoding);
} catch (Exception e) {
logger.error("组装参数失败" + e.getMessage(), e);
}
return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSPOST JSON 改为根据URL的前面几个字母(协议),来进行http或https调用。
@param url
@param encoding
@return
*/
public final static String httpsPostJson(String url, String encoding) {
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "application/json; charset=" + encoding);
return post(url, headerMap, null, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTPSDELETE 改为根据URL的前面几个字母(协议),来进行http或https调用。
@param url
@param encoding
@return
*/
public final static HttpResponse httpsDelete(String url, String encoding) {
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "application/json; charset=" + encoding);
return delete(url, headerMap, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
HTTP POST XML
@param url
@param requestXML
@param encoding
@param soapAction
@return
@throws Exception
*/
public final static String httpPostXml(String url, String requestXML, String encoding, String soapAction)
throws Exception {
Map
headerMap = new HashMap
();
headerMap.put("Content-Type", "text/xml; charset=" + encoding);
headerMap.put("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
// headerMap.put("User-Agent","Axis/1.4");
// headerMap.put("Cache-Control","no-cache");
// headerMap.put("Pragma","no-cache");
// headerMap.put("SOAPAction",soapAction);
// headerMap.put("Content-Length",requestXML.getBytes().length + "");
// 组装参数
StringEntity entity = null;
try {
entity = new StringEntity(requestXML, encoding);
} catch (Exception e) {
logger.error("httpPostXml error : ", e);
}
return post(url, headerMap, entity, encoding, url != null && url.startsWith("https:") ? "https" : "http");
}
/**
GET
@param url
@param paramsMap
@param headerMap
@param encoding
@param type http or https
@return
*/
@SuppressWarnings("deprecation")
private final static String get(String url, Map
paramsMap, Map
headerMap,
String encoding, String type) throws Exception{
String result = "";
// 组装参数
String paramStr = "";
Set
> paramEntries = paramsMap.entrySet();
for (Entry
entry : paramEntries) {
Object key = entry.getKey();
Object val = entry.getValue();
paramStr += paramStr = "&" + key + "=" + val;
}
if (!"".equals(paramStr)) {
paramStr = paramStr.replaceFirst("&", "?");
url += paramStr;
}
// 创建一个httpGet请求
HttpGet request = new HttpGet(url);
// 组装header参数
Set
> headerEntries = headerMap.entrySet();
for (Entry
entry : headerEntries) {
request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
try {
// 创建一个htt客户端
HttpClient httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
RequestConfig requestConfig =
RequestConfig.custom().setSocketTimeout(1
1000
1).setConnectTimeout(1
1000
1).build();
request.setConfig(requestConfig);
logger.debug("execute http get request,url:"+url);
// 接受客户端发回的响应
HttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
logger.debug("接口:"+url+" 返回数据:"+result);
// 得到客户段响应的实体内容
result = EntityUtils.toString(httpResponse.getEntity(), encoding);
} else {
logger.error("URL:" + url + "\tStatusCode:" + statusCode);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
return result;
}
/**
delete
@param url
@param headerMap
@param encoding
@param type
@return
*/
private final static HttpResponse delete(String url, Map
headerMap, String encoding, String type) {
String result = "";
HttpResponse httpResponse = null;
// 创建一个httpGet请求
HttpDelete request = null;
// 创建一个htt客户端
HttpClient httpClient = null;
try {
// 创建一个HttpDelete请求
request = new HttpDelete(url);
// 组装header参数
Set
> headerEntries = headerMap.entrySet();
for (Entry
entry : headerEntries) {
request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
logger.debug("Post Data to [" + url + "] ");
// 创建一个htt客户端
httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
RequestConfig requestConfig =
RequestConfig.custom().setSocketTimeout(60
1000
1).setConnectTimeout(60
1000
1).build();
request.setConfig(requestConfig);
// 接受客户端发回的响应
httpResponse = httpClient.execute(request);
// 接受客户端发回的响应
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 得到客户段响应的实体内容
result = EntityUtils.toString(httpResponse.getEntity(), encoding);
}
} catch (Exception e) {
request.abort();
String errordebug = String.format("httpclient delete failed:\nUrl=%s\nError=%s", url,
e.toString());
logger.error(errordebug, e);
} finally {
// -------- 2016-1-19 是否链接 start
// 判断request是否等于null
if (request != null) {
try {
// 释放链接
request.releaseConnection();
logger.debug("close request");
} catch (Exception e) {
logger.error("close request fail", e);
}
}
// 判断httpclient是否为null
if (httpClient != null) {
try {
// 关闭链接
httpClient.getConnectionManager().shutdown();
logger.debug("close httpClient");
} catch (Exception e) {
logger.error("close httpClient fail", e);
}
}
// -------- 2016-1-19 是否链接 start
}
return httpResponse;
}
/**
POST
@param url
@param headerMap
@param requestEntity
@param encoding
@param type
@return
*/
private final static String post(String url, Map
headerMap, HttpEntity requestEntity,
String encoding, String type) {
// String result = "";
HttpResponse httpResponse = null;
// 创建一个httpGet请求
HttpPost request = null;
// 创建一个htt客户端
HttpClient httpClient = null;
String result="";
try {
// 创建一个httpGet请求
request = new HttpPost(url);
// 组装header参数
Set
> headerEntries = headerMap.entrySet();
for (Entry
entry : headerEntries) {
request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
// 设置参数
request.setEntity(requestEntity);
logger.debug("Post Data to [" + url + "] ");
// 创建一个htt客户端
httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
RequestConfig requestConfig =
RequestConfig.custom().setSocketTimeout(1
60
1000).setConnectTimeout(1
60
1000).build();
request.setConfig(requestConfig);
// 接受客户端发回的响应
httpResponse = httpClient.execute(request);
// 接受客户端发回的响应
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 得到客户段响应的实体内容
result = EntityUtils.toString(httpResponse.getEntity(), encoding);
logger.debug("接口:"+url+" 返回数据:"+result);
}else {
logger.error("http post URL:" + url + "\tStatusCode:" + statusCode);
}
} catch (Exception e) {
request.abort();
String errordebug = String.format("httpclient post failed:\nUrl=%s\nError=%s", url, e.toString());
logger.error(errordebug, e);
throw new RuntimeException(e);
} finally {
// -------- 2016-1-19 是否链接 start
// 判断request是否等于null
if (request != null) {
try {
// 释放链接
request.releaseConnection();
logger.debug("close request");
} catch (Exception e) {
logger.error("close request fail", e);
}
}
// 判断httpclient是否为null
if (httpClient != null) {
try {
// 关闭链接
httpClient.getConnectionManager().shutdown();
logger.debug("close httpClient");
} catch (Exception e) {
logger.error("close httpClient fail", e);
}
}
// -------- 2016-1-19 是否链接 start
}
return result;
}
/**
*
@param url
@param headerMap
@param requestEntity
@param encoding
@param type
@return
*/
private final static HttpResponse nativePost(String url, Map
headerMap, HttpEntity requestEntity,
String encoding, String type) {
// String result = "";
HttpResponse httpResponse = null;
// 创建一个httpGet请求
HttpPost request = null;
// 创建一个htt客户端
HttpClient httpClient = null;
String result="";
try {
// 创建一个httpGet请求
request = new HttpPost(url);
// 组装header参数
Set
> headerEntries = headerMap.entrySet();
for (Entry
entry : headerEntries) {
request.setHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
// 设置参数
request.setEntity(requestEntity);
logger.debug("Post Data to [" + url + "] ");
// 创建一个htt客户端
httpClient = "https".equals(type) ? getHttpsClient() : new DefaultHttpClient();
RequestConfig requestConfig =
RequestConfig.custom().setSocketTimeout(1
60
1000).setConnectTimeout(1
60
1000).build();
request.setConfig(requestConfig);
// 接受客户端发回的响应
httpResponse = httpClient.execute(request);
result = EntityUtils.toString(httpResponse.getEntity(), encoding);
logger.debug("接口:"+url+" 返回数据:"+result);
} catch (Exception e) {
request.abort();
String errordebug = String.format("httpclient post failed:\nUrl=%s\nError=%s", url, e.toString());
logger.error(errordebug, e);
throw new RuntimeException(e);
} finally {
// -------- 2016-1-19 是否链接 start
// 判断request是否等于null
if (request != null) {
try {
// 释放链接
request.releaseConnection();
logger.debug("close request");
} catch (Exception e) {
logger.error("close request fail", e);
}
}
// 判断httpclient是否为null
if (httpClient != null) {
try {
// 关闭链接
httpClient.getConnectionManager().shutdown();
logger.debug("close httpClient");
} catch (Exception e) {
logger.error("close httpClient fail", e);
}
}
// -------- 2016-1-19 是否链接 start
}
return httpResponse;
}
/**
封装MAP格式的参数到BasicNameValuePair中
@param paramsMap
@return
*/
private static final List
parseMap2BasicForm(Map
paramsMap) {
List
params = new ArrayList
();;
if (paramsMap != null && paramsMap.size() > 0) {
Iterator
it = paramsMap.keySet().iterator();
String keyTmp = null;
while (it.hasNext()) {
keyTmp = it.next();
params.add(new BasicNameValuePair(keyTmp, paramsMap.get(keyTmp)));
}
}
return params;
}
/**
取已配置的HttpsClient
@return
@throws NoSuchAlgorithmException
@throws KeyManagementException
*/
private final static DefaultHttpClient getHttpsClient() throws NoSuchAlgorithmException, KeyManagementException {
// 创建默认的httpClient实例
DefaultHttpClient httpClient = new DefaultHttpClient();
X509TrustManager xtm = new X509TrustManager() { // 创建TrustManager
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return false;
}
@Override
public void verify(String arg0, SSLSocket arg1) throws IOException {}
@Override
public void verify(String arg0, X509Certificate arg1) throws SSLException {}
@Override
public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
};
SSLContext ctx;
try {
// ctx = SSLContext.getInstance("SSL", "SunJSSE");
ctx = SSLContext.getInstance("TLS");
// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
ctx.init(null, new TrustManager[] {xtm}, new java.security.SecureRandom());
// 创建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, hostnameVerifier);
// 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
} catch (Exception e) {
}
return httpClient;
}
/**
http get string from remote machine
@param url
@return
@throws IOException
@throws ClientProtocolException
*/
public static String getNetString(String url) throws IOException, ClientProtocolException {
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = httpclient.execute(get);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
// 得到客户段响应的实体内容
result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
}
get.abort();
return result;
}
// 调用osb
public static String invokeOsbInteface(String url, Map
paramMap) throws Exception {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost p = new HttpPost(url);
//p.addHeader("appid", paramMap.get("appid").toString());
// p.addHeader("appkey", paramMap.get("appkey").toString());
// paramMap.remove("appid");
// paramMap.remove("appkey");
List
params = new ArrayList
();
Iterator
iter = paramMap.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
params.add(new BasicNameValuePair(key, (String) paramMap.get(key)));
}
UrlEncodedFormEntity entity2 = new UrlEncodedFormEntity(params, "UTF-8");
p.setEntity(entity2);
RequestConfig requestConfig =
RequestConfig.custom().setSocketTimeout(OSB_TIME_OUT)
.setConnectTimeout(OSB_TIME_OUT).build();
p.setConfig(requestConfig);
HttpResponse response = httpclient.execute(p);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(response.getEntity(), "utf-8");
return result;
}
} catch (Exception e) {
logger.error(":失败" + e.getMessage(), e);
throw e;
}
return null;
}
public static String getParame(HttpServletRequest request) throws Exception {
StringBuffer sb = new StringBuffer() ;
InputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
String s = "" ;
while((s=br.readLine())!=null){
sb.append(s) ;
}
return sb.toString();
}
}
网页题目:Http工具类
文章分享:
http://cdkjz.cn/article/pdsepp.html
返回首页
了解更多建站资讯
相关资讯
vb.net数据库读取 vb调用数据库数据库
python3延时函数的简单介绍
php邮箱注册数据 php邮件
linux收发日志命令 linux操作日志命令
mysql服务器怎么启用 如何打开mysql服务器
vb.net宝山数组的简单介绍
python调取函数 python中的调用函数
怎么在guan网下载mysql 怎么在guan网下载win10
多年建站经验
多一份参考,总有益处
联系快上网,免费获得专属《策划方案》及报价
咨询相关问题或预约面谈,可以通过以下方式与我们联系
大客户专线 成都:
13518219792
座机:
028-86922220
在线咨询
提交需求