`

HttpClient4.1.2 & HtmlUnit2.9 NTLM 验证 和 Httpclient4.1.2 https/SSL

 
阅读更多
1. HttpClient4.1.2 & HtmlUnit2.9 NTLM 验证
private static final String URL = "*******";
@Test
	public void testHttpClient4_1_2Auth() throws ClientProtocolException, IOException {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
		httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
				new NTCredentials("wc24465", "*****!", null, "apac"));
		List<String> authpref = new ArrayList<String>();
		authpref.add(AuthPolicy.NTLM);
		httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
		HttpGet httpget = new HttpGet(URL);
		
	}

	@Test
	public void testHtmlUnit2_9Auth() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
		final WebClient webClient = new WebClient();

		webClient.setWebConnection(new HttpWebConnection(webClient) {

			protected synchronized AbstractHttpClient getHttpClient() {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
				httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
						new NTCredentials("wc24465", "*****", "APACCNSHZJW2336.apac.nsroot.net", "apac"));
				List<String> authpref = new ArrayList<String>();
				authpref.add(AuthPolicy.NTLM);
				httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
				return httpClient;
			}
		});

		final HtmlPage page = webClient.getPage(URL);
		
	}


public class NTLMSchemeFactory implements AuthSchemeFactory {
	public AuthScheme newInstance(final HttpParams params) {
		return new NTLMScheme(new JCIFSEngine());
	}
}



import jcifs.ntlmssp.NtlmFlags;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
import java.io.IOException;

public final class JCIFSEngine implements NTLMEngine {
	private static final int TYPE_1_FLAGS = NtlmFlags.NTLMSSP_NEGOTIATE_56 | NtlmFlags.NTLMSSP_NEGOTIATE_128 | NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2
			| NtlmFlags.NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NtlmFlags.NTLMSSP_REQUEST_TARGET;

	public String generateType1Msg(final String domain, final String workstation) throws NTLMEngineException {
		final Type1Message type1Message = new Type1Message(TYPE_1_FLAGS, domain, workstation);
		return Base64.encode(type1Message.toByteArray());
	}

	public String generateType3Msg(final String username, final String password, final String domain, final String workstation, final String challenge)
			throws NTLMEngineException {
		Type2Message type2Message;
		try {
			type2Message = new Type2Message(Base64.decode(challenge));
		} catch (final IOException exception) {
			throw new NTLMEngineException("Invalid NTLM type 2 message", exception);
		}
		final int type2Flags = type2Message.getFlags();
		final int type3Flags = type2Flags & (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER));
		final Type3Message type3Message = new Type3Message(type2Message, password, domain, username, workstation, type3Flags);
		return Base64.encode(type3Message.toByteArray());
	}
}



2. Httpclient4.1.2信任所有https/SSL证书
	@Test
	public void testHttpsLogin() throws IOException {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

		HttpParams params = new BasicHttpParams();
		params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
		params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
		params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

		ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

      HttpClient httpClient = new DefaultHttpClient(cm, params);
		}


package com.citi.ocean.errorProduct.util.test;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;

import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * This socket factory will create ssl socket that accepts self signed
 * certificate
 * 
 * @author olamy
 * @version $Id: EasySSLSocketFactory.java 765355 2009-04-15 20:59:07Z evenisse
 *          $
 * @since 1.2.3
 */
public class EasySSLSocketFactory implements LayeredSocketFactory {

	private SSLContext sslcontext = null;

	private static SSLContext createEasySSLContext() throws IOException {
		try {
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new TrustManager[] { new EasyX509TrustManager(
					null) }, null);
			return context;
		} catch (Exception e) {
			throw new IOException(e.getMessage());
		}
	}

	private SSLContext getSSLContext() throws IOException {
		if (this.sslcontext == null) {
			this.sslcontext = createEasySSLContext();
		}
		return this.sslcontext;
	}

	/**
	 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
	 *      java.lang.String, int, java.net.InetAddress, int,
	 *      org.apache.http.params.HttpParams)
	 */
	public Socket connectSocket(Socket sock, String host, int port,
			InetAddress localAddress, int localPort, HttpParams params)
			throws IOException, UnknownHostException, ConnectTimeoutException {
		int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
		int soTimeout = HttpConnectionParams.getSoTimeout(params);

		InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
		SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

		if ((localAddress != null) || (localPort > 0)) {
			// we need to bind explicitly
			if (localPort < 0) {
				localPort = 0; // indicates "any"
			}
			InetSocketAddress isa = new InetSocketAddress(localAddress,
					localPort);
			sslsock.bind(isa);
		}

		sslsock.connect(remoteAddress, connTimeout);
		sslsock.setSoTimeout(soTimeout);
		return sslsock;

	}

	/**
	 * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
	 */
	public Socket createSocket() throws IOException {
		return getSSLContext().getSocketFactory().createSocket();
		
	}

	/**
	 * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
	 */
	public boolean isSecure(Socket socket) throws IllegalArgumentException {
		return true;
	}

	/**
	 * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
	 *      java.lang.String, int, boolean)
	 */
	public Socket createSocket(Socket socket, String host, int port,
			boolean autoClose) throws IOException, UnknownHostException {
        //return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
		return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
	}

	// -------------------------------------------------------------------
	// javadoc in org.apache.http.conn.scheme.SocketFactory says :
	// Both Object.equals() and Object.hashCode() must be overridden
	// for the correct operation of some connection managers
	// -------------------------------------------------------------------

	public boolean equals(Object obj) {
		return ((obj != null) && obj.getClass().equals(
				EasySSLSocketFactory.class));
	}

	public int hashCode() {
		return EasySSLSocketFactory.class.hashCode();
	}

}


package com.citi.ocean.errorProduct.util.test;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * @author olamy
 * @version $Id: EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse $
 * @since 1.2.3
 */
public class EasyX509TrustManager
    implements X509TrustManager
{

    private X509TrustManager standardTrustManager = null;

    /**
     * Constructor for EasyX509TrustManager.
     */
    public EasyX509TrustManager( KeyStore keystore )
        throws NoSuchAlgorithmException, KeyStoreException
    {
        super();
        TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
        factory.init( keystore );
        TrustManager[] trustmanagers = factory.getTrustManagers();
        if ( trustmanagers.length == 0 )
        {
            throw new NoSuchAlgorithmException( "no trust manager found" );
        }
        this.standardTrustManager = (X509TrustManager) trustmanagers[0];
    }

    /**
     * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
     */
    public void checkClientTrusted( X509Certificate[] certificates, String authType )
        throws CertificateException
    {
        standardTrustManager.checkClientTrusted( certificates, authType );
    }

    /**
     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
     */
    public void checkServerTrusted( X509Certificate[] certificates, String authType )
        throws CertificateException
    {
        if ( ( certificates != null ) && ( certificates.length == 1 ) )
        {
            certificates[0].checkValidity();
        }
        else
        {
            standardTrustManager.checkServerTrusted( certificates, authType );
        }
    }

    /**
     * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
     */
    public X509Certificate[] getAcceptedIssuers()
    {
        return this.standardTrustManager.getAcceptedIssuers();
    }

}
分享到:
评论

相关推荐

    HttpClient4.1.2 & HtmlUnit2.9 处理文件下载

    HttpClient4.1.2 和 HtmlUnit2.9 是在Java编程中处理网络请求和网页解析的两个重要库。这篇博客文章可能详细介绍了如何利用这两个库来实现文件的下载功能。 HttpClient 是Apache基金会的一个项目,提供了丰富的HTTP...

    httpclient4.1.2 jar包

    4. **HTTPS支持**:HttpClient 4.1.2支持SSL/TLS,可以处理HTTPS连接,提供安全的网络通信。 5. **Cookie管理**:HttpClient提供了CookieSpec和CookiePolicy,用于管理Cookie,遵循多种标准和浏览器行为。 6. **...

    httpclient4.1.2.zip

    HttpClient 4.1.2也提供了对HTTPS的支持,包括证书管理和SSL/TLS协议配置。通过`SSLSocketFactory`和`X509TrustManager`,开发者可以定制安全策略,以适应不同的安全需求。 此外,HttpClient 4.1.2还提供了对...

    httpclient4.1.2 jar

    6. **认证机制**:HttpClient 支持多种认证机制,包括基本认证、摘要认证、NTLM 和 Kerberos,可满足不同安全需求。 Jersey 的主要特性有: 1. **注解驱动**:开发者可以通过在类和方法上使用 JAX-RS 注解来定义...

    httpclient-4.1.2.jar

    在Java开发中,HttpClient 4.1.2版本是广泛使用的版本之一,尤其在需要与Web服务器进行交互的应用中,其稳定性和性能得到了广大开发者的一致认可。 HttpClient 4.1.2的核心特性主要体现在以下几个方面: 1. **多...

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    这个实例主要涉及如何配置HttpClient来忽略SSL(Secure Socket Layer)验证,这对于在开发和测试环境中处理自签名证书或未认证的服务器非常有用。以下将详细介绍HttpClient的使用以及如何进行SSL验证的忽略。 首先...

    httpclient4.1.2

    HttpClient 4.1.2是该库的一个版本,它提供了丰富的功能和改进,使得开发者能够高效、灵活地处理网络通信任务。在本文中,我们将深入探讨HttpClient 4.1.2的核心概念、特性以及如何通过实例来理解和应用。 1. ...

    HttpClient4.1.2中英文文档

    - **初始化HttpClient**:了解如何创建HttpClient实例,设置基本配置,如默认主机名验证、超时设置等。 - **执行HTTP请求**:学习如何构造HttpGet、HttpPost等请求对象,并添加请求头和请求体。同时,理解如何使用...

    httpClient 4.1.2 API chm格式

    httpClient 4.1.2 API chm格式

    HttpClient4.5 实现https忽略SSL证书验证

    使用HttpClient4.5实现https请求忽略SSL证书验证工具类

    httpclient-4.1.2

    《HttpClient 4.1.2:构建高效网络通信的核心库》 HttpClient 4.1.2 是 Apache 组织提供的一款强大的 Java HTTP 客户端库,它为开发者提供了丰富的功能,使得通过 HTTP 协议进行网络通信变得更加简单、高效。这个...

    HttpClient&&HtmlParser(Crawler)网络爬虫

    HttpClient 和 HtmlParser 是在Java开发中构建网络爬虫(Crawler)时常用到的两个库。HttpClient 提供了丰富的HTTP客户端接口,可以用于发送HTTP请求并接收响应,而HtmlParser则用于解析HTML文档,提取所需的数据。...

    Commons HTTPClient4&#46;X组件应用示例

    - **高级认证机制**:支持Basic、Digest和NTLM等多种认证方式。 - **文件上传**:支持使用Multi-Part表单数据上传大文件。 - **持久连接**:支持HTTP/1.0中的KeepAlive和HTTP/1.1中的Persistance设置。 - **高效并发...

    httpclient4.5 绕过ssl认证文件访问

    请注意,这种做法仅适用于测试和非生产环境,因为完全绕过SSL验证会降低系统的安全性,易受中间人攻击。在生产环境中,始终应确保使用标准的SSL/TLS证书,并遵循最佳安全实践。 通过学习上述内容,你将能够使用...

    httpclient 绕开HTTPS证书校验

    HTTPS通过使用SSL/TLS协议来加密传输数据,保护用户的隐私和数据安全。然而,在某些特殊情况下,如进行测试、调试或者处理自签名证书的服务器,我们可能需要绕过HTTPS的证书校验。这时,`httpclient`库提供了一种...

    http远程接口调用-httpClient+跳过SSL证书校验

    总结来说,HttpClient是Java中实现HTTP/HTTPS请求的强大工具,而跳过SSL证书校验的功能在开发和测试环境中非常有用。通过创建自定义的SSLContext和HostnameVerifier,我们可以轻松地绕过SSL校验,从而简化接口调用...

    httpclient 4.1.3&3.1

    方法和原有低版本的API不太兼容,package路径变为:org.apache.http.相关包,细节使用方式请参考我的博客: http://blog.csdn.net/xieyuooo/article/details/7210846 如还有更加细致的问题,请在博客中留言,谢谢...

Global site tag (gtag.js) - Google Analytics