HttpClient+NTLM认证

1.HttpClient的使用步骤

1)创建HttpClient对象(项目中之前用的是CloseableHttpClient,这个对象无法使用NTLM认证,我换成了DefaultHttpClient)

2)创建请求方法的实例,并指定URL,根据请求方式的不同创建HttpGet或HttpPOST请求

3)如果需要发送请求参数,可以调用HttpGet/HttpPost共同的setParams(HetpParams params)方法来实现,对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4)调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接


2.项目中用到的工具类

@Component
public class HttpConnectionManager {


    private static final Integer DEFAULT_MAX_TOTAL = 200;
    private static final Integer DEFAULT_MAX_PER_ROUTE = 20;


    private final Logger logger = LoggerFactory.getLogger(getClass());


    private PoolingHttpClientConnectionManager cm;
    private Registry registry;
    private ApplicationProperties applicationProperties;


    private void init() {
        try {
            SSLContextBuilder builder = SSLContexts.custom();
            builder.loadTrustMaterial(null, (chain, authType) -> true);
            SSLContext sslContext = builder.build();
            SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(
                    sslContext, new String[] { Constants.TLS_V1_PROTOCAL, Constants.SSL_V3_PROTOCAL}, null,
                    NoopHostnameVerifier.INSTANCE);


            registry = RegistryBuilder
                    . create()
                    .register(Constants.HTTP_PROTOCAL, PlainConnectionSocketFactory.INSTANCE)
                    .register(Constants.HTTPS_PROTOCAL, sslSF)
                    .build();


            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(DEFAULT_MAX_TOTAL);
            cm.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);


        } catch (Exception ex) {
            logger.error("Can't initialize connection manager! Exiting");
            System.exit(FATAL_EXIT_CODE);
        }
    }


    public HttpConnectionManager(ApplicationProperties applicationProperties) {
        init();
        this.applicationProperties = applicationProperties;
    }

  

  //这里是我们项目对请求的一个封装,这里请求的URL配置在application.properties中

    public HttpPost defaultProxiedPostRequest(String url, String jsonStr) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(url) || StringUtils.isBlank(jsonStr)) {
            throw new InvalidParameterException("Invalid url or requestJson");
        }


        HttpPost request = new HttpPost(url);
        StringEntity se = new StringEntity(jsonStr);
        request.setEntity(se);
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
        if (StringUtils.isNotBlank(applicationProperties.getHrgenieHttpProxyHost())) {
            HttpHost proxy = new HttpHost(applicationProperties.getHrgenieHttpProxyHost(), applicationProperties.getHrgenieHttpProxyPort());
            RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
            request.setConfig(config);
        }
        return request;
    }

   

   //获取到HttpClient对象

    public CloseableHttpClient getConnection() {
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
        return httpclient;
    }

}


3.使用HttpClient加入NTLM验证的核心代码

       @SuppressWarnings("deprecation")
public V search(K k, Class respClz) {
        String snqUrl = applicationProperties.getSinequa().getUrl();
        Optional reqJson = SearchEngineUtil.objToJson(k);
        HttpPost postReq = null;

        try {

           //利用上面的类对请求做封装

            postReq = httpConnectionManager.defaultProxiedPostRequest(snqUrl, reqJson.get());
        } catch (IOException ex) {
            logger.error("Exception thrown when getting request, exception is:{}", ex);
            throw new BadSearchEngineRequestException("Invalid SINEQUA search request!");
        }


        V snqResponse = null;
        //新建一个NTLM对象,前面两个参数是用于验证的用户名和密码
        NTCredentials creds = new NTCredentials(userAu, passAu,"", "");
        // 新建一个httpclient对象,把NTLM验证加入该对象
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        
        try (CloseableHttpResponse response = httpclient.execute(postReq)) {
            snqResponse = parseResponse(response, respClz);
        } catch (IOException ex) {
            logger.error("Exception thrown when getting the response, exception is:{}", ex);
            throw new BadSearchEngineResponseException("Invalid SINEQUA search response!");
        }
        return snqResponse;

    }


附加:(用于对象和Json之间相互转换的工具类)

public class SearchEngineUtil {


    public static Optional objToJson(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = null;
        try {
            jsonStr = mapper.writeValueAsString(object);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return Optional.ofNullable(jsonStr);
    }


    public static Optional jsonToObj(String json, Class clz) {
        ObjectMapper mapper = new ObjectMapper();
        T objToRet = null;
        try {
            objToRet = mapper.readValue(json, clz);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return Optional.ofNullable(objToRet);
    }
}

你可能感兴趣的:(JAVA)