poniedziałek, grudnia 09, 2013

Apache HTTPClient 4.3 + NTLM

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultServiceUnavailableRetryStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;


public class HttpClientWrapper {
 
 private static HttpClientBuilder cb = null;
 
 public final static synchronized void initClientBuilder(int requestTimeout, int retryCount, int retryTimeout) {
  if (cb==null) {
   cb = HttpClientBuilder.create();
   cb.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE); 
   cb.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
   cb.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(retryCount, retryTimeout)); 
   RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(requestTimeout)
    .setConnectionRequestTimeout(requestTimeout).build();
   cb.setDefaultRequestConfig(requestConfig);
  }
 }
 
 private static HashMap<String,HttpClientContext> contextCache = new HashMap<String, HttpClientContext>();
 private static HashMap<String,CloseableHttpClient> clientCache = new HashMap<String, CloseableHttpClient>();
 
 public static synchronized void setAuthContext(String cookie, String user, String pass, String domain) {
  if (contextCache.get(cookie) == null) {
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(
       new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "ntlm"), 
       new NTCredentials(user, pass, "localhost", domain));
 
   AuthCache authCache = new BasicAuthCache();
   HttpClientContext context = HttpClientContext.create();
   context.setCredentialsProvider(credsProvider);
   context.setAuthCache(authCache);
   contextCache.put(cookie, context);
  }
 }
 
 public static synchronized CloseableHttpClient getClient(String cookie) {
  CloseableHttpClient cli = clientCache.get(cookie);
  if (cli==null) {
   cli = cb.build();
   clientCache.put(cookie, cli);
  }
  return cli;
 }
 
 public final static String requestReply(String cookie, String fullUrl, final String verb, String payload, final String payloadType) throws ClientProtocolException, IOException {
  CloseableHttpClient cli = getClient(cookie);
  HttpUriRequest httpRequest = null;
  if ("GET".equalsIgnoreCase(verb)) {
   httpRequest = new HttpGet(fullUrl);
  }
  else {
   HttpPost post = new HttpPost(fullUrl) {
    @Override
    public String getMethod() {     
     return verb;
    }
   };
   if (payload != null) {
    final byte[] content = payload.getBytes("UTF-8");
    post.setEntity(new AbstractHttpEntity() {
     
     @Override
     public void writeTo(OutputStream outputstream) throws IOException {
      outputstream.write(content);      
     }
     
     @Override
     public boolean isStreaming() {
      return false;
     }     
     @Override
     public boolean isRepeatable() {
      return false;
     }     
     @Override
     public long getContentLength() {
      return content.length;
     }
     @Override
     public Header getContentType() {
      return new BasicHeader("Content-Type", payloadType);
     }
     
     @Override
     public InputStream getContent() throws IOException, IllegalStateException {
      return new ByteArrayInputStream(content);
     }
    });    
   }
   httpRequest = post;
  }
  CloseableHttpResponse response = cli.execute(httpRequest, contextCache.get(cookie));
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  response.getEntity().writeTo(baos);
  return baos.toString("UTF-8");
 } 
  
 public final static void main(String[] args) throws Exception, Exception {
 initClientBuilder(60000, 3, 3000);
 setAuthContext("GET", "jan.kowalski", "passw0rd", "ENTERPRISE");
 System.out.println(requestReply("GET",
     "https://crm-test/XRMServices/2011/OrganizationData.svc/AccountSet",
     "GET", null, null)
 );
 }
}

0 komentarze: