---
title: "HttpClient4.x客户端身份验证(HTTPS安全连接)"
author: "杨胜寒"
date: "2013-05-21T13:33:03Z"
tags: []
categories: ["编程语言"]
slug: "httpclient4-x-https"
draft: false
lastmod: "2013-05-21T13:33:56Z"
id: 1872737
url: "https://yshjava.iteye.com/blog/1872737"
---

原文地址：[http://www.yshjava.cn/post/423.html](http://www.yshjava.cn/post/423.html "HttpClient4.x客户端身份验证(HTTPS安全连接)")

 

最近Apache HttpClient发布了最新的4.3版本，据说有很多的改进，加入了新的设计思想和理念，使API更加简洁有力，闲来无事，做个Demo尝尝鲜。

在以前的3.x版本中，HttpClient就已经支持HTTPS连接了，但是代码写的比较多，而且用起来感觉挺别扭的，同样的功能，到了4这里，明显得简单清爽多了。

如下是来自官方的一个例子，稍加改造，并翻译了注释：

```
package cn.ysh.studio.crawler.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * 演示如何使用HttpClient向需要身份验证的目标服务器发送HTTP请求
 * 
 * @author Shenghany
 * @date 2013-5-19
 */
public class ClientAuthentication {

	public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
			//添加证书
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

			//创建GET请求
            HttpGet httpget = new HttpGet("https://localhost/protected");

            System.out.println("executing request" + httpget.getRequestLine());
			//执行请求
            HttpResponse response = httpclient.execute(httpget);
			//获得响应实体
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
			//销毁实体
            EntityUtils.consume(entity);
        } finally {
            // 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
            httpclient.getConnectionManager().shutdown();
        }
    }
	
}
```

 

原创文章，转载请注明出处：[http://www.yshjava.cn/post/423.html](http://www.yshjava.cn/post/423.html "HttpClient4.x客户端身份验证(HTTPS安全连接)")