java jdk原生的http请求工具类
- package com.base;
- 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;
- /**
- *
- * @ClassName: HttpUtils
- * @Description:http请求工具类
- * @author: zhouyy
- * @date: 2019年10月14日 下午3:50:34
- *
- */
- public class HttpUtils {
- private static final String CTYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8";
- private static final String CTYPE_JSON = "application/json; charset=utf-8";
- private static final String charset = "utf-8";
- private static HttpUtils instance = null;
- public static HttpUtils getInstance() {
- if (instance == null) {
- return new HttpUtils();
- }
- return instance;
- }
- public static void main(String[] args) throws SocketTimeoutException, IOException {
- String resp = getInstance().postJson("http://localhost:8080/test/test", "{\"custCmonId\":\"12345678\",\"custNo\":\"111\",\"custNo111\":\"706923\"}");
- System.out.println(resp);
- }
- 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);
- }
- /**
- *
- * <p>@Description: </p>
- * @Title doRequest
- * @author zhouyy
- * @param method 请求的method post/get
- * @param url 请求url
- * @param requestContent 请求参数
- * @param connectTimeout 请求超时
- * @param readTimeout 响应超时
- * @param ctype 请求格式 xml/json等等
- * @param headerMap 请求header中要封装的参数
- * @return
- * @throws SocketTimeoutException
- * @throws IOException
- * @date: 2019年10月14日 下午3:47:35
- */
- 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(requestContent != null && requestContent.trim().length() >0){
- 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 (msg != null && msg.trim().length() >0) {
- 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();
- }
- }
非原著,借鉴大神!
https://www.cnblogs.com/jpfss/p/10063666.html
java jdk原生的http请求工具类的更多相关文章
- Http请求工具类(Java原生Form+Json)
package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...
- java模板模式项目中使用--封装一个http请求工具类
需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- Java判断不为空的工具类总结
1.Java判断是否为空的工具类,可以直接使用.包含,String字符串,数组,集合等等. package com.bie.util; import java.util.Collection; imp ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
- Http请求工具类 httputil
package com.snowfigure.kits.net; import java.io.BufferedReader; import java.io.IOException; import j ...
- HttpClientUtils:Http请求工具类
HttpClientUtils:Http请求工具类 Scala:HttpClientUtils Scala:HttpClientUtils import java.io.IOException imp ...
随机推荐
- PostgreSQL通过解析日志,获取数据库增量变化,pg_recvlogical
1.首先用该工具来看我们的日志变化,需要先将test_decoding插件编译并安装(进入contrib,编译安装即可) 创建一个slot: SELECT * FROM pg_create_logic ...
- CAS导致的ABA问题及解决:时间戳原子引用AtomicReference、AtomicStampedReference
1.CAS导致ABA问题: CAS算法实现一个重要前提需要取出内存中某时刻的数据并在当下时刻比较并交换,那么在这个时间差中会导致数据的变化. 比如:线程1从内存位置V中取出A,这时线程2也从V中取出A ...
- springboot笔记-thymeleaf
简介:Thymeleaf 是⾯向 Web 和独⽴环境的现代服务器端 Java 模板引擎,能够处理 HTML.XML.JavaScript.CSS 甚至纯文本.Thymeleaf 的作用域在 HTML ...
- python——元组方法及字符串方法
元组方法 Tup.count():计算元组中指定元素出现的次数 Tup.count('c') Tup.index():在元组中从左到右查找指定元素,找到第一个就返回该元素的索引值 Tup.index( ...
- 配置ShiroFilter需要注意的问题(Shiro_DelegatingFilterProxy)
ShiroFilter的工作原理 ShiroFilter:DelegatingFilterProxy作用是自动到Spring 容器查找名字为shiroFilter(filter-name)的bean并 ...
- 2019-11-29-msbuild-项目文件常用判断条件
title author date CreateTime categories msbuild 项目文件常用判断条件 lindexi 2019-11-29 08:36:48 +0800 2019-7- ...
- laravel 学习之第二章
Controller Controller之Request 获取请求的值 namespace App\Http\Controllers; use Illuminate\http\Request; pu ...
- Git 查看远端仓库地址
git remote -v
- 004-SaltStack入门篇之数据系统Grains、Pillar
1.什么是Grains? Grains是saltstack的组件,用于收集salt-minion在启动时候的信息,又称为静态信息.可以理解为Grains记录着每台Minion的一些常用属性,比如CPU ...
- 021-Zabbix4.2对IIS监控摸索记录
Zabbix是很强大,但是相关的细节技术文档貌似很少,摸索之路就显得异常难. 度娘搜了下,关于Zabbix对IIS的监控资料确实有,确实也讲如何操作了,但是细细按照对方的要求操作下,总是缺数据,no ...