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:建议下 ...
随机推荐
- Code obfuscatio (翻译!)
Description Kostya likes Codeforces contests very much. However, he is very disappointed that his so ...
- Thunder团队Beta周贡献分分配结果
小组名称:Thunder 项目名称:爱阅app 组长:王航 成员:李传康.翟宇豪.邹双黛.苗威.宋雨.胡佑蓉.杨梓瑞 分配规则 规则1:基础分,拿出总分的20%(8分)进行均分,剩下的80%(32分) ...
- Calculator Part Ⅰ (代码规范化修改)
GitHub/object-oriented 本次参照的C++代码规范 有一些规范内容在文件中其实并未提及,比如:空格的使用,修改的时候真的是一头雾水--根据文件中的例子,发现了一些文字部分没有提到的 ...
- Spring中Controller和RequestMapping的详解
先看一个简单的实例: @Controller @RequestMapping("/hello") public class anyTypeController{ @RequestM ...
- 最多水容器(M)
题目 给定n个非负整数a 1,a 2,...,a n,其中每个代表坐标(i,a i)处的一个点.绘制n条垂直线,使得线i的两个端点处于(i,a i)和(i,0)处.找到两条线,它们与x轴一起形成一个容 ...
- autoCAD 2008 Win7 64位, win8 64位 安装 燕秀工具箱 yanxiu.cui 文件下载
Win7 64位, win8 64位 安装 燕秀工具箱 , 提示没有权限. 网站上下载燕秀工具箱, 安装后. 提示权限不够. 解决办法如下; 1. CAD, 权限修改. 2. 下载 yanxiu.cu ...
- win7主题/默认账户图片路径
账户图片位置 C:\ProgramData\Microsoft\User Account Pictures 主题位置 C:\Windows\Resources
- SpringBoot使用servletAPI与异常处理
工程结构: 主方法类: package com.boot.servlet.api.bootservlet; import org.springframework.boot.SpringApplicat ...
- hdu2295-Radar
有n个城市,\(m\)个雷达,\(k\)个操作员,每个操作员只能操作一个雷达.每个雷达的覆盖范围是一个以雷达坐标为中心的圆,所有雷达的覆盖半径是相同的. 现在给出这\(n\)个城市,\(m\)个雷达的 ...
- poj2018——Best Cow Fences
Description Farmer John's farm consists of a long row of N (1 <= N <= 100,000)fields. Each fie ...