package com.tzx.cc.common.constant.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Set; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.commons.lang.StringUtils; /**
* http请求工具类
*
* @author zhangyong
*
*/
public class HttpUtils {
private final String CTYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8";
private final String CTYPE_JSON = "application/json; charset=utf-8";
private final String charset = "utf-8"; private static HttpUtils instance = null; public static HttpUtils getInstance() {
if (instance == null) {
return new HttpUtils();
}
return instance;
} private class DefaultTrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
} public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
} /**
* 以application/json; charset=utf-8方式传输
*
* @param url
* @param requestContent
* @return
* @throws SocketTimeoutException
* @throws IOException
*/
public String postJson(String url, String jsonContent)
throws SocketTimeoutException, IOException {
return doRequest("POST", url, jsonContent, 15000, 15000, CTYPE_JSON,
null);
} /**
* POST 以application/x-www-form-urlencoded;charset=utf-8方式传输
*
* @param url
* @param requestContent
* @return
* @throws SocketTimeoutException
* @throws IOException
*/
public String postForm(String url) throws SocketTimeoutException,
IOException {
return doRequest("POST", url, "", 15000, 15000, CTYPE_FORM, null);
} /**
* POST 以application/x-www-form-urlencoded;charset=utf-8方式传输
*
* @param url
* @param requestContent
* @return
* @throws SocketTimeoutException
* @throws IOException
*/
public String postForm(String url, Map<String, String> params)
throws SocketTimeoutException, IOException {
return doRequest("POST", url, buildQuery(params), 15000, 15000,
CTYPE_FORM, null);
} /**
* POST 以application/x-www-form-urlencoded;charset=utf-8方式传输
*
* @param url
* @param requestContent
* @return
* @throws SocketTimeoutException
* @throws IOException
*/
public String getForm(String url) throws SocketTimeoutException,
IOException {
return doRequest("GET", url, "", 15000, 15000, CTYPE_FORM, null);
} /**
* POST 以application/x-www-form-urlencoded;charset=utf-8方式传输
*
* @param url
* @param requestContent
* @return
* @throws SocketTimeoutException
* @throws IOException
*/
public String getForm(String url, Map<String, String> params)
throws SocketTimeoutException, IOException {
return doRequest("GET", url, buildQuery(params), 15000, 15000,
CTYPE_FORM, null);
} private String doRequest(String method, String url, String requestContent,
int connectTimeout, int readTimeout, String ctype,
Map<String, String> headerMap) throws SocketTimeoutException,
IOException {
HttpURLConnection conn = null;
OutputStream out = null;
String rsp = null;
try {
conn = getConnection(new URL(url), method, ctype, headerMap);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout); if(!StringUtils.isEmpty(requestContent)){
out = conn.getOutputStream();
out.write(requestContent.getBytes(charset));
} rsp = getResponseAsString(conn);
} finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
conn = null;
}
return rsp;
} private HttpURLConnection getConnection(URL url, String method,
String ctype, Map<String, String> headerMap) throws IOException {
HttpURLConnection conn;
if ("https".equals(url.getProtocol())) {
SSLContext ctx;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0],
new TrustManager[] { new DefaultTrustManager() },
new SecureRandom());
} catch (Exception e) {
throw new IOException(e);
}
HttpsURLConnection connHttps = (HttpsURLConnection) url
.openConnection();
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn = connHttps;
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept",
"text/xml,text/javascript,text/html,application/json");
conn.setRequestProperty("Content-Type", ctype);
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return conn;
} private String getResponseAsString(HttpURLConnection conn)
throws IOException {
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset, conn);
} else {
String msg = getStreamAsString(es, charset, conn);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":"
+ conn.getResponseMessage());
} else {
return msg;
}
}
} private String getStreamAsString(InputStream stream, String charset,
HttpURLConnection conn) throws IOException {
try {
Reader reader = new InputStreamReader(stream, charset); StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
} return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
} private String buildQuery(Map<String, String> params) throws IOException {
if (params == null || params.isEmpty()) {
return "";
} StringBuilder query = new StringBuilder();
Set<Map.Entry<String, String>> entries = params.entrySet();
boolean hasParam = false; for (Map.Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=")
.append(URLEncoder.encode(value, charset));
}
return query.toString();
}
}

Http请求工具类(Java原生Form+Json)的更多相关文章

  1. java jdk原生的http请求工具类

    package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...

  2. java模板模式项目中使用--封装一个http请求工具类

    需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  5. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  6. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

  7. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  8. C# http请求工具类

    /// <summary> /// Http请求操作类之HttpWebRequest /// </summary> public class HttpHelper { #reg ...

  9. Http请求工具类 httputil

    package com.snowfigure.kits.net; import java.io.BufferedReader; import java.io.IOException; import j ...

随机推荐

  1. BZOJ3238: [Ahoi2013]差异(后缀数组)

    Description Input 一行,一个字符串S Output 一行,一个整数,表示所求值 Sample Input cacao Sample Output 54 解题思路: 看到lcp,想到了 ...

  2. ubuntu14中 memcached安装与使用

    第一步,先安装lib-event 下载lib-event  的包http://libevent.org/ 下载完之后,解压安装 ./configure –prefix=/usr (或 ./config ...

  3. sql 高性能存储过程分页

    USE [Lyjjr] GO /****** Object: StoredProcedure [dbo].[P_ViewPage] Script Date: 05/29/2015 17:18:56 * ...

  4. HTML的SEO(搜索引擎优化)标准

    HTML的SEO(搜索引擎优化)标准 一.总结 这个做seo的时候要多看,做网站优化的时候 1. SEO(搜索引擎优化):通过总结搜索引擎的排名规律,对网站进行合理优化,使你的网站在百度和Google ...

  5. jquery中$(dom).each()和$(dom).length的使用

    1.$(dom).each();在dom处理上用的比较多. $(selector).each(function(index,element){ //selector会遍历当前页面里所有匹配的jquer ...

  6. CodeVs——T 3305 水果姐逛水果街Ⅱ

    http://codevs.cn/problem/3305/  时间限制: 2 s  空间限制: 256000 KB  题目等级 : 钻石 Diamond 题解  查看运行结果     题目描述 De ...

  7. [Angular] Implement a custom form component by using control value accessor

    We have a form component: <label> <h3>Type</h3> <workout-type formControlName=& ...

  8. 【微信】微信获取TOKEN,以及储存TOKEN方法,Spring quartz让Token永只是期

    官网说明 access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token.开发人员须要进行妥善保存. access_token的存储至少要保留512个字符空间.ac ...

  9. liunx基本操作常用命令

    liunx通常用作服务器,运行服务器软件,服务器要等待,类似超市学关键命令操作 内核,外壳 shell命令跟内核打交道用的是发行版本,不是内核,Radhat公司的CentOS,阿里巴巴也用这个 liu ...

  10. 【习题 5-6 UVA-1595】Symmetry

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 每一个y坐标的点都找中点. 看看中点是不是都一样就好. [代码] #include <bits/stdc++.h> us ...