java https post请求并忽略证书,参数放在body中
1 新建java类,作用是绕过证书用
package cn.smartercampus.core.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
2 https post请求
package cn.smartercampus.core.util; import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map; public class HttpsPostUtil {
//添加主机名验证程序类,设置不验证主机
private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}; //添加信任主机
private static void trustAllHosts() {
// 创建不验证证书链的信任管理器 这里使用的是x509证书
TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
} public void checkClientTrusted(X509Certificate[] chain, String authType) {
} public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}};
// 安装所有信任的信任管理器
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接,SSLSocket对象是由SSLSocketFactory生成的。
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 发送post 数据
* @param urls
* @return
*/
public static String heart(String urls, String param, String contentType, String method) {
StringBuffer sb=new StringBuffer();
DataOutputStream out = null;
BufferedReader responseReader = null;
InputStream in1 = null;
try {
trustAllHosts();
// 创建url资源
URL url = new URL(urls);
// 建立http连接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
// 设置不用缓存
conn.setUseCaches(false);
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置传递方式
conn.setRequestMethod(method);
//System.out.println(conn.getRequestMethod());
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
// byte[] data = (param).getBytes();
// // 设置文件长度
// conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", param);
// 开始连接请求
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
// 写入请求的字符串
out.writeBytes(param);
out.flush(); //System.out.println(conn.getResponseCode()); // 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
System.out.println("连接成功");
// 请求返回的数据
in1 = conn.getInputStream();
String readLine;
responseReader = new BufferedReader(new InputStreamReader(in1));
while((readLine=responseReader.readLine()) != null){
sb.append(readLine).append("\n");
}
} else {
System.out.println("error++");
}
} catch (Exception e) { } finally {
try {
if (null != responseReader)
responseReader.close();
if (null != in1)
in1.close();
} catch(Exception e) {}
try {
out.close();
} catch(Exception e) {}
} return sb.toString(); } /**
* 发送post 数据
* @param urls
* @return
*/
public static String sendPost(String urls, String param, String contentType, String method) {
StringBuffer sb=new StringBuffer();
DataOutputStream out = null;
BufferedReader responseReader = null;
InputStream in1 = null;
try {
trustAllHosts();
// 创建url资源
URL url = new URL(urls);
// 建立http连接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
// 设置不用缓存
conn.setUseCaches(false);
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置传递方式
conn.setRequestMethod(method);
//System.out.println(conn.getRequestMethod());
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
// byte[] data = (param).getBytes();
// // 设置文件长度
// conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("Content-Type", contentType);
// 开始连接请求
conn.connect();
out = new DataOutputStream(conn.getOutputStream());
// 写入请求的字符串
out.writeBytes(param);
out.flush(); //System.out.println(conn.getResponseCode()); // 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
System.out.println("连接成功");
// 请求返回的数据
in1 = conn.getInputStream();
String readLine;
responseReader = new BufferedReader(new InputStreamReader(in1));
while((readLine=responseReader.readLine()) != null){
sb.append(readLine).append("\n");
}
} else {
System.out.println("error++");
}
} catch (Exception e) { } finally {
try {
if (null != responseReader)
responseReader.close();
if (null != in1)
in1.close();
} catch(Exception e) {}
try {
out.close();
} catch(Exception e) {}
} return sb.toString(); } /**
* map转url参数
*/
public static String map2Url(Map<String, String> paramToMap) {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue();
if (!StringUtils.isEmpty(value)) {
url.append(value);
}
}
return url.toString();
} public static void main(String[] args) {
System.out.println("123");
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", "xx.cn");
params.put("client_secret", "UY83SNFJWLU32NJSLJIK");
params.put("code", "40ce7f41d6562e47dbdc33593ddce1b46444cdb93514b3aaced7be90eb51a16f");
params.put("grant_type", "authorization_code");
params.put("redirect_uri", "xxn/index.jsp");
//要发送的POST请求url?Key=Value&Key2=Value2&Key3=Value3的形式
//application/json;charset=UTF-8 application/x-www-form-urlencoded;charset=UTF-8
String sb = sendPost("https://id.pdedu.sh.cn/connect/token",map2Url(params),"application/x-www-form-urlencoded;charset=UTF-8","POST");
//System.out.println(sb); } }
java https post请求并忽略证书,参数放在body中的更多相关文章
- java在访问https资源时,忽略证书信任问题 (转)
java程序在访问https资源时,出现报错sun.security.validator.ValidatorException: PKIX path building failed: sun.secu ...
- java https单向认证(忽略认证)并支持http基本认证
https单向认证(忽略认证)并支持http基本认证, 温馨提示 1,jar包要导入对 2,有匿名类编译要注意 3,欢迎提问,拿走不谢!背景知识 Https访问的相关知识中,主要分为单向验证和双向验证 ...
- java遍历http请求request的所有参数实现方法
方法一: 通过程序遍历http请求的所有参数放到hashmap中,用的时候方便了. 如果参数值有中文,那么需要在程序中添加filter转码,或者在下面程序里,对paramValue转码 Map map ...
- java https客户端请求
String pathname = Test3.class.getResource("/client.jks").getFile(); System.out.println(pat ...
- HTTP-java访问https资源时,忽略证书信任问题,代码栗子
java程序在访问https资源时,出现报错 sun.security.validator.ValidatorException: PKIX path building failed: sun.sec ...
- java自动化测试-http请求post
继上文的get请求http://www.cnblogs.com/xuezhezlr/p/7667995.html的简单讲解后,这篇文章大概说一下我所遇到的主要的post请求以及他的测试代码 上文介绍到 ...
- Fiddler怎么可以抓取https的请求包
对于https的协议是带有安全的功能,所有有一些的https的协议是无法抓到的,所以需要通过设置filler中来对,来使用filler的方式的来抓取到https的请求包,那么如何使用filler中抓取 ...
- RestTemplate请求https忽略证书认证
RestTemplate是Spring提供的用于访问Rest服务的客户端,提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率.RestTemplate 默认使用J2SE提供的方式( ...
- java HttpClient 忽略证书的信任的实现 MySSLProtocolSocketFactory
当不需要任何证书访问https时,java中先实现一个MySSLProtocolSocketFactory类忽略证书的信任 package com.tgb.mq.producer.utils; imp ...
随机推荐
- 性能测试之Jmeter插件安装
使用Jmeter的实际过程中,需要使用到很多插件,比如json的插件,还有就是做websocket接口测试的时候需要下载websocket的插件,虽然官方提供了插件下载的地址,但是知道为什么每次访问的 ...
- Appium连接夜神模拟器,模拟手势点击(tap)
# -*- coding:utf-8 -*- from appium import webdriver from time import sleep desired_caps ={ 'platform ...
- httprunner学习5-参数化与数据驱动
前言 参数化是自动化测试离不开的话题,httprunner里面只要把上一篇声明变量学会了,参数化也就自然会了. 不同的地方在于声明变量时对应值只有一个,参数化是多个值,存放在list里面. httpr ...
- 2019牛客暑期多校训练营(第五场)B:generator 1 (10进制快速幂)
题意:给定x0,x1,a,b,满足xi=a*xi-1+b*xi-2: 求xn,n<10^(10^6): 思路:10进制快速幂裸题.降幂来写好像也是可以的,但是循环节不是phi(mod),所以数学 ...
- 【大数据】Hadoop单机安装配置
1.解压缩hadoop-2.7.6.tar.gz到/home/hadoop/Soft目录中 2.创建软链接,方便hadoop升级 ln -s /home/hadoop/Soft/hadoop-2.7 ...
- redisql 试用
redisql 是一个redis 模块,可以让redis 支持sql 查询,基于rust编写 具有以下特性 快速,每秒130k的插入 使用标准sql 容易操作,基于redis,使用标准的redis 二 ...
- C# VS常用操作
VS点击项目,就会打开文件,其实我只是想选中而已, 在这个地方可以改. 原文:https://blog.csdn.net/yellowegg/article/details/12217309
- [洛谷P3092]【[USACO13NOV]没有找零No Change】
状压\(DP\) + 二分 考虑构成:\(k<=16\)所以根据\(k\)构造状压\(dp\),将所有硬币的使用情况进行状态压缩 考虑状态:数组\(dp[i]\)表示用\(i\)状态下的硬币可以 ...
- shell 换行与不换行
test.sh: echo -e "hello w\norld!"echo -e "hello w\c"echo "orld!" 输出 bo ...
- Java——获取网页内容并在本地生成HTML文件
使用java.net包下的URL类,可以将一个网页(链接)封装成一个URL对象. URL对象有一个openStream()方法,使用该方法可以获取该网页的输入流,我们可以通过读取输入流的方式获得网页的 ...