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

httpclient使用NTLM协与https协议访问双向认证站点

阅读更多

 

  上篇中提到了在NTLM协议中使用HTTPS协议访问需要双向认证的问题,这里会给出方案和相应代码。

 

 

public static String getWithNTCredentialAndSSLClientAuth(String url,boolean needProxy,int msTimeOut) throws MalformedURLException{
		log.info("--get url:[" + url + "]");
		String responseBody = null;
		HttpMethod getMethod = new GetMethod(url);
		if(msTimeOut>0) {
			getMethod.getParams().setSoTimeout(msTimeOut);
		}
		log.info("--queryString:" + getMethod.getQueryString());
		Protocol authhttps = new Protocol("https",new AuthSSLProtocolSocketFactory(), 443); 
        Protocol.registerProtocol("https",authhttps);
		HttpClient httpClient = new HttpClient();
		if (needProxy) {
			String proxyUrl = "xxx.xxx.xxx.xxx";
			String proxyPort ="8080";
			String proxyUser ="xxxxxx";
			String proxyPassword ="xxxxx";
			String domain="xxxxx.COM";
			httpClient.getHostConfiguration().setProxy(proxyUrl,Integer.parseInt(proxyPort));
			List authPrefs = new ArrayList(2);
			authPrefs.add(AuthPolicy.NTLM);
			httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,"Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1"); 
			httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
			// 如果代理需要密码验证,这里设置用户名密码
			NTCredentials ntc=new NTCredentials(proxyUser, proxyPassword,proxyUrl,domain);
			httpClient.getState().setProxyCredentials(AuthScope.ANY,ntc);
		}
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			log.info("http get url:" + getMethod.getURI());
			log.info("----http status code:" + statusCode);
			if (statusCode == HttpStatus.SC_OK || statusCode==HttpStatus.SC_PARTIAL_CONTENT) {
				responseBody = getMethod.getResponseBodyAsString();
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return responseBody;
	}

 

   关键代码

	Protocol authhttps = new Protocol("https",new AuthSSLProtocolSocketFactory(), 443); 
        Protocol.registerProtocol("https",authhttps);

  此处代码指定使用https协议,而此协议的创建需要传入

AuthSSLProtocolSocketFactory

 这是SSL协议认证工厂实例,这个实例主要提供 SSLContext 即SSL上下文,示例代码中,该上下文由SSLTool类提供,而 SSLContext的创建需要服务器端证书,客户端证书,客户端证书。示例代码中,我们把配置我们存放在/configs/tenpay.properties文件中。

server_cert_file_name=D:/sslfile/xxxx.pem   服务器端证书文件路径
client_cert_file_name=D:/sslfile/xxxx.pfx   客户端证书文件路径 
client_cert_password=xxxxx客户端证书密码 

 

代码中,测试方法在src\com\apache\test\https\HttpClientUtil.java  中

有问题可加QQ 359709421

 

如果您觉得我的文章给了您帮助,请为我买一杯饮料吧!以下是我的支付宝,意思一下我将非常感激!
分享到:
评论
1 楼 wilddonkey 2014-08-09  
好文章,说的很详细。

相关推荐

Global site tag (gtag.js) - Google Analytics