`
zzzzzz5530041
  • 浏览: 32939 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

HTTPConnector 发送请求

 
阅读更多
package com.****util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.net.ssl.KeyManagerFactory;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

 
 

public class HttpConnector {

	static Log logger = LogFactory.getLog(HttpConnector.class);

	 public HttpConnector(){
		 this.init();
	 }
	private String URLs[];
	private String proxyHost = null;
	private String proxyPort = "8080";
	private String retryCount = "1";
	private String sslPort = "443";
	private String algorithm = KeyManagerFactory.getDefaultAlgorithm();
	private String storeKey;
	private String trustKey;
	private String protocolType ;
	private String keyStoreName;
	private String trustStoreName;
	private String[] subUrls;

	 
	/**
	 * init parameters 
	 */
	public void init(){
		logger.debug("enter httpconnector init()");
		this.URLs=new String[]{Utils.getProperty("jpc.httpconnector.urls")};
		logger.debug("URLs ===>"+URLs[0]);
		this.proxyPort=Utils.getProperty("jpc.httpconnector.proxyport");   
		logger.debug("proxyPort ===>"+proxyPort);
		this.retryCount=Utils.getProperty("jpc.httpconnector.retrycount") ;  
		if(StringUtils.isEmpty(this.retryCount)){
			this.retryCount="1";
		}
		logger.debug("retryCount ===>"+retryCount);
		this.algorithm=KeyManagerFactory.getDefaultAlgorithm();
		this.storeKey=Utils.getProperty("jpc.httpconnector.storekey") ; 
		logger.debug("storeKey ===>"+storeKey);
		this.trustStoreName=Utils.getProperty("jpc.httpconnector.truststorename"); 
		logger.debug("trustStoreName ===>"+trustStoreName);
		this.keyStoreName=Utils.getProperty("jpc.httpconnector.keystorename"); 
		logger.debug("keyStoreName ===>"+keyStoreName);
		this.subUrls=new String[]{Utils.getProperty("jpc.httpconnector.suburls")}; 
		logger.debug("subUrls ===>"+subUrls[0]);
		this.protocolType=Utils.getProperty("jpc.httpconnector.protocoltype"); 
		logger.debug("protocolType ===>"+protocolType);
		this.sslPort=Utils.getProperty("jpc.httpconnector.sslport" ); 
		logger.debug("sslPort ===>"+sslPort);
		if(StringUtils.isEmpty(this.sslPort)){
			this.retryCount="443";
		}
		this.trustKey=Utils.getProperty("jpc.httpconnector.trustkey"); 
		logger.debug("trustKey ===>"+trustKey);
	}
	 

	public String sendEntity(RequestEntity requestEntiry)throws MessagingException {
		final String debugHeader = getClass().getName() + ".sendEntity(): ";
		HttpClient client = new HttpClient();
		InputStream stream;
		String responseStr = "";
		this.proxyHost = this.proxyHost == null|| this.proxyHost.trim().equals("") ? null : this.proxyHost
				.trim();
		if (this.proxyHost != null) {
			client.getHostConfiguration().setHost(this.proxyHost,
					Integer.parseInt(this.proxyPort));
		}

		if ("https".equals(protocolType)) {
			Protocol https = new Protocol(protocolType,
					new JPCSSLProtocolSocketFactory(keyStoreName, storeKey
							.toCharArray(), algorithm, trustStoreName, trustKey
							.toCharArray(), algorithm, null),Integer.parseInt(sslPort));
			logger.debug("https  "+https);
			Protocol.registerProtocol(protocolType, https);
			
		}
		PostMethod method = new PostMethod(this.URLs[0] + subUrls[0]);
		
		client.getParams().setAuthenticationPreemptive(true);
		logger.debug("client====>"+client);
		method.setRequestEntity(requestEntiry);
		method.setDoAuthentication(true);
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(Integer.parseInt(retryCount), false));
		logger.debug("method  "+method);
		try {
			client.executeMethod(method);
			String statusCode = String.valueOf(method.getStatusCode());
			if (statusCode.startsWith("4") || statusCode.startsWith("5")) {
				logger.error(debugHeader
								+ "For the URL: "
								+ this.URLs[0]
								+ ", the status code is other than 200. Actual Status Code is : "
								+ statusCode
								+ " and Hence trying with other urls. ");
			} else {
				stream = method.getResponseBodyAsStream();
				logger.debug("stream  "+stream);
				responseStr = convertStream(stream);
			}
		} catch (Exception e) {
			logger.error("Exception occurs:" + e.getMessage());
			throw new ConnectorException(debugHeader
					+ "Exception Occured with  the url(s) = " + this.URLs[0]
					+ subUrls[0] + ", and returning null");
		} finally {
			if (method != null) {
				method.releaseConnection();
			}
		}
		return responseStr;
	}
	/**
	 * convert inputstream to String
	 * @param stream comes from host
	 * @return
	 * @throws IOException
	 */
	private String convertStream(InputStream stream) throws IOException {

		BufferedInputStream bis = new BufferedInputStream(stream);
		int c = -1;
		StringBuffer sbf = new StringBuffer("");
		if ((c = bis.read()) != -1) {
			do {
				sbf.append(String.valueOf((char) c));
			} while ((c = bis.read()) != -1);
		}
		return sbf.toString();
	}
}

package com.***.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class JPCSSLProtocolSocketFactory implements SecureProtocolSocketFactory {
	private static final Log logger = LogFactory.getLog(JPCSSLProtocolSocketFactory.class);
    private SSLContext sslContext;
    private SSLSocketFactory sslSocketFactory;
	public JPCSSLProtocolSocketFactory(String keyStorePath, char[] keystoreStorepass,
			String keyManagerFactoryAlgorithm, String trustStorePath, char[] truststoreStorepass,
			String trustManagerFactoryAlgorithm, String keystoreType) {
		try {
			logger.debug("enter JPCSSLProtocolSocketFactory constructor...");
			StringBuffer sb = new StringBuffer();
			logger.debug(sb.append("keyStorePath="+keyStorePath+",keystoreStorepass="+new String(keystoreStorepass)+",keyManagerFactoryAlgorithm="+keyManagerFactoryAlgorithm
					+",trustStorePath="+trustStorePath+",truststoreStorepass="+new String(truststoreStorepass)+",trustManagerFactoryAlgorithm="+trustManagerFactoryAlgorithm+",keystoreType="+keystoreType));

			if (trustStorePath == null || truststoreStorepass == null || trustManagerFactoryAlgorithm == null) {
			    throw new IllegalArgumentException("trustStorePath == null || truststoreStorepass == null || trustManagerFactoryAlgorithm == null");
			}
			
			KeyManager[] kms = null;
			TrustManager[] tms = null;
			KeyStore keystore = null;
			if (keyStorePath != null && keyStorePath.trim().length() > 0) {

			    if (keystoreStorepass == null || keyManagerFactoryAlgorithm == null) {
			        throw new IllegalArgumentException("keystoreStorepass == null || keyManagerFactoryAlgorithm == null");
			    }

			    if (keystoreType == null || keystoreType.trim().length() == 0) {
			        keystore = loadKeyStore(keyStorePath, keystoreStorepass);
			    } else {
			         
						keystore = loadKeyStore(keystoreType, keyStorePath, keystoreStorepass);
			    }
			    KeyManagerFactory kmFactory =KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
			    logger.debug("kmFactory === "+kmFactory);
				kmFactory.init(keystore, keystoreStorepass);
			    kms = kmFactory.getKeyManagers();
			    logger.debug("kms === "+kms);
			    if (new String(truststoreStorepass).trim().length() == 0) {
			        logger.debug("truststoreStorepass:(" + truststoreStorepass.toString() + ") set to null");
			        truststoreStorepass = null;
			      }
			      KeyStore truststore = loadKeyStore(trustStorePath, truststoreStorepass);
			      logger.debug("truststore === "+truststore);
			      TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(trustManagerFactoryAlgorithm);
			      logger.debug("tmFactory === "+tmFactory);
			      tmFactory.init(truststore);
			      logger.debug("tmFactory === "+tmFactory);
			      
			      tms = tmFactory.getTrustManagers();
			      logger.debug("tms === "+tms);
			      this.sslContext = SSLContext.getInstance("SSL");
			      logger.debug("sslContext === "+sslContext);
			      this.sslContext.init(kms, tms, null);
			      this.sslSocketFactory = this.sslContext.getSocketFactory();
			      logger.debug("sslSocketFactory === "+sslSocketFactory);
			}
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnrecoverableKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Socket createSocket(final String host, final int port, final InetAddress clientHost, int clientPort) throws IOException {
        return sslSocketFactory.createSocket(host, port, clientHost, clientPort);
    }

    /**
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
     */
    public Socket createSocket(final String host, final int port) throws IOException {
        return sslSocketFactory.createSocket(host, port);
    }

    /**
     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
     */
    public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
        return sslSocketFactory.createSocket(socket, host, port, autoClose);
    }
/*
 * 	//invoked after invoke httpClient.executeMethod() method
 * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String, int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams)
 */
    public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3, HttpConnectionParams arg4) throws IOException, UnknownHostException, ConnectTimeoutException {
    
    	return sslSocketFactory.createSocket(arg0, arg1,arg2,arg3);
    }
	public static KeyStore loadKeyStore(String keyStoreFilePath, char keyStorePassword[]) {
        try {
            return loadKeyStore(KeyStore.getDefaultType(), keyStoreFilePath, keyStorePassword);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
            	logger.debug("error when load the key store,will return null");
            }
        }

        return null;
    }
	public static KeyStore loadKeyStore(String keyStoreType, String keyStoreResource, char keyStorePassword[]) throws Exception {
        InputStream in = null;
        try {
            KeyStore keystore;
            try {
                KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                logger.debug("keystore=="+keyStore);
                in = JPCSSLProtocolSocketFactory.class.getResourceAsStream(keyStoreResource);
                logger.debug("in=="+in);
                if (in == null)
                    throw new Exception("file [" + keyStoreResource + "] does not exist");
                keyStore.load(in, keyStorePassword);
                logger.debug("keyStore=="+keyStore);
                keystore = keyStore;
                logger.debug("keystore  "+keystore);
            } catch (IOException ioe) {
                throw new Exception(ioe.getMessage(), ioe);
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            }
            return keystore;
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException ioe1) {
                }
        }
    }

}
 
/**调用*/
public static String generateSMAL(String customerID,String samlentryPoint) throws Exception{
	  	logger.debug("enter generateSMAL ()");
		StringBuffer credentialData =new StringBuffer();
		credentialData.append("<CUSTOMERID>").append(customerID).append("</CUSTOMERID>")
		.append("<ENTRYPOINTID>").append(samlentryPoint).append("</ENTRYPOINTID>");
		String issueraddress =Utils.getProperty("jpcegainsamlissueraddress");
		logger.debug("issueraddress===>"+issueraddress);
		
		logger.debug("credentialData ==="+credentialData);
		VelocityContext velocityContext = new VelocityContext();
	    velocityContext.put("credentialData",credentialData);
	    velocityContext.put("issueraddress",issueraddress);
		VelocityEngine velocity = new VelocityEngine();
		String soapTokenRequestFilePath=Utils.getProperty("jpcegainsoaptokenrequestfilepath");
		logger.debug("soapTokenRequestFilePath ===>"+soapTokenRequestFilePath);
		velocity.setProperty("file.resource.loader.path", soapTokenRequestFilePath); 
		 StringWriter messageBody =null;
		velocity.init();
		Template template = velocity.getTemplate("SoapTokenRequest.vm", "UTF-8");
		messageBody = new StringWriter();
		template.merge(velocityContext, messageBody);
		logger.debug("SoapTokenRequest request body==="+messageBody.toString());
		HttpConnector hc=new HttpConnector();
		logger.debug("HttpConnector ===="+hc);
		StringRequestEntity requestEntity = new StringRequestEntity(messageBody.toString(), "text/xml", "UTF-8");
		logger.debug("requestEntity =="+requestEntity);
	    String responseMessage = hc.sendEntity(requestEntity);
	    logger.debug("responseMessage ==== "+responseMessage);
	    String token=parseResponse(responseMessage);
	    logger.debug("SAML token==="+token);
	    return token;
	}
  private static String parseResponse(String responseMessage) throws Exception {
	// TODO Auto-generated method stub
	logger.debug("responseMessage====>"+responseMessage);
	String token="";
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(new ByteArrayInputStream(responseMessage.getBytes()));
		NodeList nl = doc.getElementsByTagName("csts:SAMLResponse");
		Node my_node = nl.item(0);
		logger.debug("my_node====>"+my_node);
		token = my_node.getFirstChild().getNodeValue();
	} catch (Exception e) {
		
		logger.error("facing error when parse response=="+e.getMessage());
		e.printStackTrace();
		throw new Exception("facing error when parse response=="+e.getMessage());
	}
	return token;
}
 import javax.net.ssl.KeyManagerFactory; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.citi.ito.jpc.common.Utils; import com.*******.messaging.exception.ConnectorException; import com.*******.exception.MessagingException; public class HttpConnector { static Log logger = LogFactory.getLog(HttpConnector.class); public HttpConnector(){ this.init(); } private String URLs[]; private String proxyHost = null; private String proxyPort = "8080"; private String retryCount = "1"; private String sslPort = "443"; private String algorithm = KeyManagerFactory.getDefaultAlgorithm(); private String storeKey; private String trustKey; private String protocolType ; private String keyStoreName; private String trustStoreName; private String[] subUrls; /** * init parameters */ public void init(){ logger.debug("enter httpconnector init()"); this.URLs=new String[]{Utils.getProperty("jpc.httpconnector.urls")}; logger.debug("URLs ===>"+URLs[0]); this.proxyPort=Utils.getProperty("jpc.httpconnector.proxyport"); logger.debug("proxyPort ===>"+proxyPort); this.retryCount=Utils.getProperty("jpc.httpconnector.retrycount") ; if(StringUtils.isEmpty(this.retryCount)){ this.retryCount="1"; } logger.debug("retryCount ===>"+retryCount); this.algorithm=KeyManagerFactory.getDefaultAlgorithm(); this.storeKey=Utils.getProperty("jpc.httpconnector.storekey") ; logger.debug("storeKey ===>"+storeKey); this.trustStoreName=Utils.getProperty("jpc.httpconnector.truststorename"); logger.debug("trustStoreName ===>"+trustStoreName); this.keyStoreName=Utils.getProperty("jpc.httpconnector.keystorename"); logger.debug("keyStoreName ===>"+keyStoreName); this.subUrls=new String[]{Utils.getProperty("jpc.httpconnector.suburls")}; logger.debug("subUrls ===>"+subUrls[0]); this.protocolType=Utils.getProperty("jpc.httpconnector.protocoltype"); logger.debug("protocolType ===>"+protocolType); this.sslPort=Utils.getProperty("jpc.httpconnector.sslport" ); logger.debug("sslPort ===>"+sslPort); if(StringUtils.isEmpty(this.sslPort)){ this.retryCount="443"; } this.trustKey=Utils.getProperty("jpc.httpconnector.trustkey"); logger.debug("trustKey ===>"+trustKey); } public String sendEntity(RequestEntity requestEntiry)throws MessagingException { final String debugHeader = getClass().getName() + ".sendEntity(): "; HttpClient client = new HttpClient(); InputStream stream; String responseStr = ""; this.proxyHost = this.proxyHost == null|| this.proxyHost.trim().equals("") ? null : this.proxyHost .trim(); if (this.proxyHost != null) { client.getHostConfiguration().setHost(this.proxyHost, Integer.parseInt(this.proxyPort)); } if ("https".equals(protocolType)) { Protocol https = new Protocol(protocolType, new JPCSSLProtocolSocketFactory(keyStoreName, storeKey .toCharArray(), algorithm, trustStoreName, trustKey .toCharArray(), algorithm, null),Integer.parseInt(sslPort)); logger.debug("https "+https); Protocol.registerProtocol(protocolType, https); } PostMethod method = new PostMethod(this.URLs[0] + subUrls[0]); client.getParams().setAuthenticationPreemptive(true); logger.debug("client====>"+client); method.setRequestEntity(requestEntiry); method.setDoAuthentication(true); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(Integer.parseInt(retryCount), false)); logger.debug("method "+method); try { client.executeMethod(method); String statusCode = String.valueOf(method.getStatusCode()); if (statusCode.startsWith("4") || statusCode.startsWith("5")) { logger.error(debugHeader + "For the URL: " + this.URLs[0] + ", the status code is other than 200. Actual Status Code is : " + statusCode + " and Hence trying with other urls. "); } else { stream = method.getResponseBodyAsStream(); logger.debug("stream "+stream); responseStr = convertStream(stream); } } catch (Exception e) { logger.error("Exception occurs:" + e.getMessage()); throw new ConnectorException(debugHeader + "Exception Occured with the url(s) = " + this.URLs[0] + subUrls[0] + ", and returning null"); } finally { if (method != null) { method.releaseConnection(); } } return responseStr; } /** * convert inputstream to String * @param stream comes from host * @return * @throws IOException */ private String convertStream(InputStream stream) throws IOException { BufferedInputStream bis = new BufferedInputStream(stream); int c = -1; StringBuffer sbf = new StringBuffer(""); if ((c = bis.read()) != -1) { do { sbf.append(String.valueOf((char) c)); } while ((c = bis.read()) != -1); } return sbf.toString(); } }

 ##################SAML#######################
jpcegainsamlentrypoint=1000
jpcegainsamlissueraddress=*****
jpcegainsoaptokenrequestfilepath=/*****

#################JPC HTTP CONNECTOR######################

jpc.httpconnector.urls=*****
jpc.httpconnector.proxyport=8080
jpc.httpconnector.retrycount=1
jpc.httpconnector.storekey=*****
jpc.httpconnector.truststorename=/resources/SSO/EGAIN/saixu33_truststore.jks
jpc.httpconnector.keystorename=/resources/SSO/EGAIN/saixu33_keystore.jks
jpc.httpconnector.suburls=/*****
jpc.httpconnector.protocoltype=https
jpc.httpconnector.sslport=443
jpc.httpconnector.trustkey=citi1234

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics