浏览器可以作为客户端向服务器发送Http请求,当需要访问后台或第三方Restful接口时,也可以用java实现客户端直接发get/post请求,获取数据。

https客户端


import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; /**
* 基于HttpsURLConnection实现客户端https请求
*
*/
public class HttpsClientDemo {
private static final String METHOD_GET = "GET";
private static final String METHOD_POST = "POST"; /**
* doGet
*/
private static void httpsGet(String url) throws NoSuchAlgorithmException, KeyManagementException, IOException {
// 创建连接对象
HttpsURLConnection connection = getHttpsURLConnection(url, METHOD_GET);
connection.connect();
System.out.println("cipersuit used:" + connection.getCipherSuite()); // 读取连接响应内容
getresponse(connection);
} /**
* doPost
*/
private static void httpsPost(String url, String params) throws NoSuchAlgorithmException, IOException, KeyManagementException {
// 创建连接对象
HttpsURLConnection connection = getHttpsURLConnection(url, METHOD_POST);
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect(); // 获取URLConnection对象对应的输出流
PrintWriter out = null;
try {
out = new PrintWriter(connection.getOutputStream());
// 发送请求参数
out.print(params);
out.flush();
} finally {
if (out != null) {
out.close();
}
}
getresponse(connection);
} /**
* 读取连接响应内容
*/
private static void getresponse(HttpsURLConnection connection) throws IOException { BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
System.out.println(sb.toString());
System.out.println("responseMsg:" + connection.getResponseMessage() + "; responseCode:" + connection.getResponseCode());
} finally {
if (br != null) {
br.close();
}
}
} /**
* 获取连接对象
*/
private static HttpsURLConnection getHttpsURLConnection(String url, String method) throws IOException, NoSuchAlgorithmException, KeyManagementException {
URL myUrl = new URL(url);
// 创建连接对象
HttpsURLConnection connection = (HttpsURLConnection) myUrl.openConnection();
connection.setRequestMethod(method);
// 设置SSLSocketFactory对象(若不指定算法套,getSslContext().getSocketFactory()即可)
connection.setSSLSocketFactory(new MySSLSocketFactory());
// 验证hostname,全部允许
connection.setHostnameVerifier((hostname, sslSession) -> true); // 设置通用请求属性
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8"); return connection;
} public static void main(String[] args) throws Exception {
String url = "https://***"; httpsGet(url);
// httpsPost(url, "username=admin&password=admin@1234&forceLogin=false");
}
}

指定ssl算法套

如果是需要设置客户端算法套,可以通过继承SSLSocketFactory重写其createSocket()方法,自行设置SSL算法套。

import javax.net.ssl.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; /**
* 重写createSocket方法,设置算法套
*/
public class MySSLSocketFactory extends SSLSocketFactory {
private static final String[] cipherSuites = new String[]{
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"}; private static SSLContext sslContext = null; // 设置算法套
private void setSSLParams(SSLSocket sslSocket) {
sslSocket.setUseClientMode(true);
sslSocket.setEnabledCipherSuites(cipherSuites);
} /**
* 创建SSLContext对象,使用默认信任管理器初始化
*/
private static SSLContext getSslContext() {
if (sslContext == null) {
try {
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
SSLContext.setDefault(sslContext);
}
return sslContext;
} @Override
public String[] getDefaultCipherSuites() {
return cipherSuites;
} @Override
public String[] getSupportedCipherSuites() {
return cipherSuites;
} @Override
public Socket createSocket(Socket socket, String host, int port, boolean b) throws IOException {
SSLSocket sslSocket = (SSLSocket) getSslContext().getSocketFactory().createSocket(socket, host, port, b);
setSSLParams(sslSocket);
return sslSocket;
} @Override
public Socket createSocket(String host, int port) throws IOException {
SSLSocket sslSocket = (SSLSocket) getSslContext().getSocketFactory().createSocket(host, port);
setSSLParams(sslSocket);
return sslSocket;
} @Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
SSLSocket sslSocket = (SSLSocket) getSslContext().getSocketFactory().createSocket(host, port, localHost, localPort);
setSSLParams(sslSocket);
return sslSocket;
} @Override
public Socket createSocket(InetAddress host, int port) throws IOException {
SSLSocket sslSocket = (SSLSocket) getSslContext().getSocketFactory().createSocket(host, port);
setSSLParams(sslSocket);
return sslSocket;
} @Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
SSLSocket sslSocket = (SSLSocket) getSslContext().getSocketFactory().createSocket(address, port, localAddress, localPort);
setSSLParams(sslSocket);
return sslSocket;
} /**
* SSL信任管理类
*/
private static class DefaultTrustManager implements X509TrustManager { @Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
} @Override
public X509Certificate[] getAcceptedIssuers() {
return null;
} } }

HTTPS客户端的java实现的更多相关文章

  1. JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求

    JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求 哇,一看标题怎么这么长啊,其实意思很简单,哥讨厌用HTTP Client做POST与GET提交 觉得那个毕竟是别人写 ...

  2. C#使用Thrift简介,C#客户端和Java服务端相互交互

    C#使用Thrift简介,C#客户端和Java服务端相互交互 本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实 ...

  3. Java与WCF交互(二):WCF客户端调用Java web service【转】

    原文:http://www.cnblogs.com/downmoon/archive/2010/08/25/1807982.html 在上篇< Java与WCF交互(一):Java客户端调用WC ...

  4. 转载——Java与WCF交互(二):WCF客户端调用Java Web Service

    在上篇< Java与WCF交互(一):Java客户端调用WCF服务>中,我介绍了自己如何使用axis2生成java客户端的悲惨经历.有同学问起使用什么协议,经初步验证,发现只有wsHttp ...

  5. 客户端使用java,服务端使用c++的corba编程环境搭建

    我们先用c++实现服务端和客户端,然后再用java编写客户端. 1. 首先安装omniORB,omniORB提供 omniidl命令,以及一些头文件和库. omniORB一般是需要你自己进行编译. 2 ...

  6. .net 客户端调用java或.net webservice进行soapheader验证

    .net 客户端调用java或.net webservice进行soapheader验证 最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservi ...

  7. log4j的1.2.15版本,在pom.xml中的顶层project报错错误: Failure to transfer javax.jms:jms:jar:1.1 from https://maven-repository.dev.java.net/nonav/repository......

    在动态网站工程中,添加了Pom依赖,当添加log4j的1.2.15版本依赖时,在pom.xml中的顶层project报错错误: Failure to transfer javax.jms:jms:ja ...

  8. Hbase入门(五)——客户端(Java,Shell,Thrift,Rest,MR,WebUI)

    Hbase的客户端有原生java客户端,Hbase Shell,Thrift,Rest,Mapreduce,WebUI等等. 下面是这几种客户端的常见用法. 一.原生Java客户端 原生java客户端 ...

  9. java https客户端请求

    String pathname = Test3.class.getResource("/client.jks").getFile(); System.out.println(pat ...

随机推荐

  1. Arduino与NodeMCU——联网

    我们现在要使用Arduino IDE来配置您的ESP8266芯片.这是使用该芯片的好方法,因为您可以使用着名的Arduino IDE对其进行编程,并重复使用几个现有的Arduino库.如果尚未完成,请 ...

  2. 30天轻松学习javaweb_修改tomcat的servlet模板

    在MyEclipse目录下搜索com.genuitec.eclipse.wizards 得到搜索结果 com.genuitec.eclipse.wizards_9.0.0.me201108091322 ...

  3. 在Windows Server2016中安装SQL Server2016(转)

    在Windows Server2016中安装SQL Server2016(转) 转自: http://blog.csdn.net/yenange/article/details/52980135 参考 ...

  4. FVWM_SMALLEST_CONFIG

    ... # ----------------------------------------------------------------- # HANDBOOK: # http://yaoqian ...

  5. TIKA环境配置

    本章将指导完成设置Apache Tika在Windows和Linux的配置过程.用户管理是必要的,同时安装了Apache Tika. 系统要求 JDK Java SE 2 JDK 1.6 或以上 内存 ...

  6. python面试题之你如何管理不同版本的代码?

    答案: 版本管理!被问到这个问题的时候,你应该要表现得很兴奋,甚至告诉他们你是如何使用Git(或是其他你最喜欢的工具)追踪自己和奶奶的书信往来.我偏向于使用Git作为版本控制系统(VCS),但还有其他 ...

  7. 快速求1~n的k!,k的逆元

    1.求1~n的k! 2.求inv(k!) 3.inv((k-1)!)=inv(k!)*k%mod 4.inv(k)=inv(k!)*((k-1)!)%mod 如 https://www.cnblogs ...

  8. Java KMP算法代码

    1. KMP 算法(字符串匹配算法)较 BF(朴素的字符串匹配)算法有哪些改进 1) 在主串和子串匹配的过程中,主串不再回退,只改变子串的比较位置. 2) 为子串生成对应的next数组,每次匹配失败, ...

  9. element中的tree组件实现菜单分配

    返回的菜单数据 tree组件的使用 <el-tree ref="menuList" // :data="menuList" // 展示数据 :props= ...

  10. JZOJ5153:树形图求和

    Description Input Output HINT 题解: 一种很直观的想法是通过矩阵生成树求树形图方法数ans以及不包含某一条边i的树形图方法数ans[i],则答案为Σ(ans-ans[i] ...