`
杨胜寒
  • 浏览: 284760 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

HttpClient4.x客户端身份验证(HTTPS安全连接)

阅读更多

 

原文地址:http://www.yshjava.cn/post/423.html

 

最近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

0
5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics