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:建议下 ...
随机推荐
- Python中的list
list的创建 1 字面量 >>>L = [1, 2, 3] [1, 2, 3] 2 通过iterable可迭代对象,比如str对象,range对象,map对象 >>&g ...
- Discover the Web(栈模拟)
Description Standard web browsers contain features to move backward and forward among the pages rece ...
- [zt]手把手教你写对拍程序(PASCAL)
谁适合看这篇文章? ACMERS,OIERS或其它参加算法竞赛或需要算法的人 对操作系统并不太熟悉的人 不会写对拍的人 在网上找不到一个特别详细的对拍样例的人 不嫌弃我写的太低幼的人 前言 在NOIP ...
- 【week4】技术随笔psp
本周psp
- linux的几个发行网站
Red Hat: http://www.redhat.com Fedora: http://fedoraproject.org/ Mandriva: http://www.mandriva ...
- 不能将多个项传入“Microsoft.Build.Framework.ITaskItem”类型的参数
项目编译报错: ”对于“GenerateApplicationManifest”任务的“InputManifest”参数是无效值.不能将多个项传入“Microsoft.Build.Framework. ...
- 【.Net】Visual Studio的调试技巧
这是我写的关于VS2010和.Net4发布的博客系列的第26篇. 今天的博文包含了一些有用的能用于VS的调试技巧. 我的朋友Scott Cate(他写了很多很好的关于VS使用技巧和窍门的博客)最近向我 ...
- 【hdu4734】F(x) 数位dp
题目描述 对于一个非负整数 $x=\overline{a_na_{n-1}...a_2a_1}$ ,设 $F(x)=a_n·2^{n-1}+a_{n-1}·2^{n-2}+...+a_2·2^1+ ...
- [LouguT30212]玩游戏
题面在这里 description 对于\(k=1,2,...,t\),求\[\frac{1}{nm}\sum_{i=1}^{n}\sum_{j=1}^{m}(a_i+b_j)^k\] 对\(9982 ...
- BZOJ4009 & 洛谷3242 & LOJ2113:[HNOI2015]接水果——题解
https://www.lydsy.com/JudgeOnline/problem.php?id=4009 https://www.luogu.org/problemnew/show/P3242 ht ...