Httpclient 调用 HTTPS 加密通道的Restful服务

为 Restful 增加 SSL 证书,保证数据在传输中安全。

证书有两类,一类是授信办颁发构的证书,另一类是自己创建的证书,两种证书使用效果上一样。

授信证书的跟证书默认已经安装在操作系统,浏览器中,访问时会出现锁头跟绿色标识。这种证书是需要购买的,因为这些证书厂商每年都要像微软,苹果等等操作系统厂商支付一定费用。

最近火狐公司发表声明,将取消“沃通”根证书,这就意味着这所有沃通用户都会变成 红叉叉。

对于内部业务不需要对外提供服务,例如Restful 服务,我见意自己创建证书,如果你需要让浏览器地址栏变成绿色,只需将你的根证书导入进去就可可以了。

本文节选择《Netkiller Java 手札》

21.1.3. Get https 接口

环境 Nginx SSL(openssl自颁发),nginx 通过proxy_pass连接 Tomcat

下面是 nginx 配置

server {
    listen 443 ssl spdy;
    server_name api.netkiller.cn;

    ssl_certificate /etc/nginx/ssl/api.netkiller.cn.crt;
    ssl_certificate_key /etc/nginx/ssl/api.netkiller.cn.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 60m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    charset utf-8;
    access_log  /var/log/nginx/api.netkiller.cn.access.log;
    error_log  /var/log/nginx/api.netkiller.cn.error.log;

    location / {
        proxy_pass      http://127.0.0.1:7000;
        proxy_http_version 1.1;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}			

21.1.1. Maven

			<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.netkiller</groupId>
	<artifactId>example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>

	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>			

21.1.3. HTTPS

21.1.3.1. Get https 接口

环境 Nginx SSL(openssl自颁发),nginx 通过proxy_pass连接 Tomcat

下面是 nginx 配置

server {
    listen 443 ssl spdy;
    server_name api.netkiller.cn;

    ssl_certificate /etc/nginx/ssl/api.netkiller.cn.crt;
    ssl_certificate_key /etc/nginx/ssl/api.netkiller.cn.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 60m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    charset utf-8;
    access_log  /var/log/nginx/api.netkiller.cn.access.log;
    error_log  /var/log/nginx/api.netkiller.cn.error.log;

    location / {
        proxy_pass      http://127.0.0.1:7000;
        proxy_http_version 1.1;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}				

下面是 Java 程序

				package cn.netkiller.example;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

public class NginxAndOpenSSLAndTomcatAndHttpclient {
	public static void main(String[] args) throws ParseException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
		SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(builder.build());
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslFactory).build();

		HttpGet httpGet = new HttpGet("https://neo:netkiller@api.netkiller.cn/v1/news/today.json");
		CloseableHttpResponse response = httpclient.execute(httpGet);
		try {
			System.out.println(response.getStatusLine());
			HttpEntity entity = response.getEntity();
			String responseBody = EntityUtils.toString(entity, "UTF-8");
			System.out.println(responseBody.toString());
		} finally {
			response.close();
		}
	}
}				

如果遇到配置问题,可以看一下《Netkiller Linux Web 手札》

21.1.3.2. POST json 数据

			 	package cn.netkiller.example;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

public class HttpClientSSLPost {

	public HttpClientSSLPost() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SSLContextBuilder builder = new SSLContextBuilder();
		try {
			builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

			SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(builder.build());
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslFactory).build();

			HttpPost httpPost = new HttpPost("https://neo:YruuUCNXKe@api.netkiller.cn/v1/member/create.json");
			httpPost.addHeader("content-type", "application/json");
			httpPost.addHeader("Accept", "application/json");

			HttpEntity httpEntity = new StringEntity("{\"name\":\"neo\", \"nickname\":\"netkiler\",\"age\":\"18\"}", "UTF-8");
			
			httpPost.setEntity(httpEntity);

			CloseableHttpResponse response = httpclient.execute(httpPost);

			System.out.println(response.getStatusLine());
			HttpEntity entity = response.getEntity();
			String responseBody = EntityUtils.toString(entity, "UTF-8");
			System.out.println(responseBody.toString());
			response.close();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		finally {

		}
	}

}

如果遇到配置问题,可以看一下《Netkiller Linux Web 手札》

原文发布于微信公众号 - Netkiller(netkiller-ebook)

原文发表时间:2016-09-11

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏石奈子的Java之路

原 荐 Java9之HttpClientAP

1382
来自专栏wannshan(javaer,RPC)

利用spring-ws 现实soap webservice服务

背景:有的系统还用soap协议来做webservice.特别要和他们对接的时候。我们需要实现一套。 今天说说,利用spring-ws来(部署,调用)webse...

5186
来自专栏杨龙飞前端

formvalidation表单验证

33710
来自专栏Java成神之路

20180831_jar包冲突2_天安微信httpclient冲突

在本地用tomcat跑时,是正常的。但是在服务器上用weblogic跑时,却报了这个异常。

431
来自专栏向治洪

android cookie持久化

在解析网页信息的时候,需要登录后才能访问,所以使用httpclient模拟登录,然后把cookie保存下来,以供下一次访问使用,这时就需要持久化cookie中的...

2459
来自专栏菩提树下的杨过

JAVA CDI 学习(5) - 如何向RESTFul Service中注入EJB实例

RESTFul Service中如果要注入EJB实例,常规的@Inject将不起作用,在Jboss中,应用甚至都启动不起来(因为@Inject注入失败),解决方...

1847
来自专栏FreeBuf

九种姿势运行Mimikatz

*本文原创作者:R1ngk3y,本文属FreeBuf原创奖励计划,未经许可禁止转载

973
来自专栏宝哥技术杂谈

一桩由ssl证书过期引起的血案

公司全部站点升级了https,升级过程由同事们完成,我没有过问细节。ssl证书使用的是阿里云 的【Symantec免费版 SSL】一年免费。

1265
来自专栏余林丰

外观模式

 外观模式又称为门面模式,为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。我们还是用通俗的语言来解释这句话...

1638
来自专栏用户3030674的专栏

java Http消息传递之POST和GET两种方法--通过实用工具类来获取服务器资源

/** * 实用工具类来获取服务器资源 * * get方法传送数据 * * 1、通过path设定传送方式 * 2、创建客户端 *...

564

扫描关注云+社区