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 条评论
登录 后参与评论

相关文章

来自专栏码匠的流水账

spring cloud gateway的stripPrefix配置

本文主要研究下spring cloud gateway的stripPrefix配置

1151
来自专栏小狼的世界

Aptana的破解

最近写JS比较多,常常苦恼与没有一个顺手的IDE。Editplus虽然用的熟,不过那个的效率太低而且代码看起来也很不方便,经过一个多月的试用,发现了一款好用的编...

802
来自专栏有趣的django

微信小程序实战–集阅读与电影于一体的小程序项目(七)

1292
来自专栏大魏分享(微信公众号:david-share)

从四个java源码构文件建一个机票预定业务的规则引擎(下篇)

1013
来自专栏Hongten

彩色照片转换为黑白照片(Color image converted to black and white picture)

This blog will be talking about the color image converted to black and white pic...

772
来自专栏java系列博客

javax.mail 实现邮件发送

1667
来自专栏编程之旅

iOS 全局禁止横屏,但视频播放界面选择性横屏的解决办法

有时我们的APP并没有适配横屏的需求,但是在个别视频播放界面,我们需要在播放视频的时候横屏,退出全屏的时候不能横屏,但是有时候并没有原生API并没有给出解决方案...

1702
来自专栏码匠的流水账

聊聊spring cloud gateway的RedirectToGatewayFilter

本文主要研究下spring cloud gateway的RedirectToGatewayFilter

911
来自专栏JackieZheng

Java豆瓣电影爬虫——模拟登录的前世今生与验证码的爱恨情仇

前言 并不是所有的网站都能够敞开心扉让你看个透彻,它们总要给你出些难题让你觉得有些东西是来之不易的,往往,这也更加激发你的激情和斗志! 从《为了媳妇的一张号,...

3276
来自专栏用户画像

HttpClient 发送get请求并返回Json数据

http://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid...

481

扫码关注云+社区