Java进行http请求工具类代码(支持https)
package com.guyezhai.modules.utils; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager; public class HttpUtils { /**
* POST请求远程http页面
*
* @param contentUrl
* @param params
* @return
*/
public static String post(String contentUrl, Map<String, Object> params) {
StringBuilder contentBuilder = new StringBuilder();
HttpURLConnection connection = null;
DataOutputStream out = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(contentUrl).openConnection();
// 设置Socket超时
connection.setConnectTimeout(10000);
connection.setReadTimeout(20000);
// Post 请求不能使用缓存
connection.setUseCaches(false);
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
connection.setDoOutput(true);// 是否输入参数
// 要注意的是connection.getOutputStream会隐含的进行connect
connection.connect(); out = new DataOutputStream(connection.getOutputStream());
StringBuilder parambBuilder = new StringBuilder();
if (params != null) {
for (Entry<String, Object> e : params.entrySet()) {
parambBuilder.append(e.getKey()).append("=").append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8")).append("&");
}
parambBuilder.deleteCharAt(parambBuilder.length() - 1);
}
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(parambBuilder.toString());
out.flush(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); int buffer = 0;
while ((buffer = reader.read()) != -1) {
contentBuilder.append((char) buffer);
} } catch (Exception e) {
// 异常处理
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} if (connection != null) {
connection.disconnect();
}
}
return contentBuilder.toString();
} /**
* Get方法请求
*
* @param contentUrl
* @return
*/
public static String get(String contentUrl) {
StringBuilder contentBuilder = new StringBuilder();
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
connection = (HttpURLConnection) new URL(contentUrl).openConnection();
// 设置Socket超时
connection.setConnectTimeout(10000);
connection.setReadTimeout(20000);
connection.setRequestMethod("GET");
connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); int buffer = 0;
while ((buffer = reader.read()) != -1) {
contentBuilder.append((char) buffer);
}
} catch (Exception e) {
// 异常处理
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return contentBuilder.toString();
} /**
* POST请求远程https页面
*
* @param contentUrl
* @param params
* @return
*/
public static String postHttps(String contentUrl, Map<String, Object> params) {
StringBuilder contentBuilder = new StringBuilder();
HttpsURLConnection connection = null;
DataOutputStream out = null;
BufferedReader reader = null;
try {
HostnameVerifier hnv = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}; X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} @Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
}; X509TrustManager[] xtmArray = new X509TrustManager[] { trustManager };
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, xtmArray, new java.security.SecureRandom()); if (sslContext != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
HttpsURLConnection.setDefaultHostnameVerifier(hnv); connection = (HttpsURLConnection) new URL(contentUrl).openConnection();
// 设置Socket超时
connection.setConnectTimeout(10000);
connection.setReadTimeout(20000);
// Post 请求不能使用缓存
connection.setUseCaches(false);
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
connection.setDoOutput(true);// 是否输入参数
connection.connect(); out = new DataOutputStream(connection.getOutputStream());
StringBuilder parambBuilder = new StringBuilder();
if (params != null) {
for (Entry<String, Object> e : params.entrySet()) {
parambBuilder.append(e.getKey()).append("=").append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8")).append("&");
}
parambBuilder.deleteCharAt(parambBuilder.length() - 1);
}
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(parambBuilder.toString());
out.flush(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); int buffer = 0;
while ((buffer = reader.read()) != -1) {
contentBuilder.append((char) buffer);
}
} catch (Exception e) {
// 异常处理
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return contentBuilder.toString();
} }
Java进行http请求工具类代码(支持https)的更多相关文章
- 基于JAVA原生HTTP请求工具类 httphelper
原文地址;http://lushuifa.iteye.com/blog/2313896 import java.io.BufferedReader; import java.io.BufferedWr ...
- Java之网络请求工具类(依赖:org.apache.http;注:HttpClient 4.4,HttpCore 4.4)
到此处可以去下载依赖包:http://hc.apache.org/downloads.cgi import java.util.List; import org.apache.http.HttpSta ...
- Java模仿http请求工具类
package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...
- Java 实现 Http 请求工具类
package com.demo.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...
- Java 发送 Http请求工具类
HttpClient.java package util; import java.io.BufferedReader; import java.io.IOException; import java ...
- java模板模式项目中使用--封装一个http请求工具类
需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...
- Http请求工具类(Java原生Form+Json)
package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...
- java jdk原生的http请求工具类
package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
随机推荐
- Java微笔记(2)
Java 中方法的重载 一,如果同一个类中包含了两个或两个以上方法名相同.方法参数的个数.顺序或类型不同的方法,则称为方法的重载,也可称该方法被重载了 二,.判断方法重载的依据: 1. 必须是在同一个 ...
- java — 值传递和引用传递
在 Java 应用程序中永远不会传递对象,而只传递对象引用.因此是按引用传递对象.Java 应用程序按引用传递对象这一事实并不意味着 Java 应用程序按引用传递参数.参数可以是对象引用,而 Java ...
- 【Redis】- 安装为windows服务
1.安装redis服务 echo install redis-server redis-server.exe --service-install redis.windows.conf --loglev ...
- 数字证书认证这点事, SSL/TLS,OpenSSL
1.概念 数字证书 HTTPS请求时,Server发给浏览器的认证数据,用私钥签名,并且告诉浏览器公钥,利用公钥解密签名,确认Server身份. 证书还会指明相应的CA,CA能确认证书是否真的是CA颁 ...
- Thread.Sleep(0)
理解Thread.Sleep函数 我们可能经常会用到 Thread.Sleep 函数来使线程挂起一段时间.那么你有没有正确的理解这个函数的用法呢? 思考下面这两个问题: 1.假设现在是 2008-4- ...
- java.awt.AWTError: Can't connect to X11 window server using ':20' as the value of the DISPLAY variable
1.使用pio在Linux服务器上创建window文件时,需要使用到Linux的图形界面服务,出现以下问题需确认用户权限. 参考文献:https://zhidao.baidu.com/question ...
- ICE checkbox 用法
Hello everybody, I have a datable which contain multiple lines gotten from database, in the header o ...
- BZOJ 1786 配对(DP)
如果我们直接令dp[i][j]为前i个位置第i个位置填j所产生的逆序对的最少数.这样是不满足无后效性的. 但是如果发现对于两个-1,如果前面的-1填的数要大于后面的-1填的数.容易证明把他们两交换结果 ...
- 【bzoj2091】[Poi2010]The Minima Game dp
题目描述 给出N个正整数,AB两个人轮流取数,A先取.每次可以取任意多个数,直到N个数都被取走.每次获得的得分为取的数中的最小值,A和B的策略都是尽可能使得自己的得分减去对手的得分更大.在这样的情况下 ...
- hdu 1162 Eddy's picture (最小生成树)
Eddy's picture Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)To ...