https连接提交

12 篇文章 0 订阅

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import mpi.days.cert.CertificateUnit;
import mpi.days.common.Constants;
import mpi.days.common.Rescode;
import mpi.days.exception.PayException;
import mpi.days.http.BaseHttpClient;
import mpi.days.http.HttpStatusUnit;
import mpi.days.http.HttpUtils;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class HttpClientSSL implements BaseHttpClient {

	private static Logger logger = Logger.getLogger(HttpClientSSL.class);

	private String url;

	private InputStream resultInputStream;

	private byte[] resultInputByte;

	private String hostURL;

	private String appURL;

	private String postCharSet = Constants.CHARSET_UTF8;

	private static final int URL_LEN = 8;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public HttpClientSSL(String url) {
		super();
		this.url = url;
		if (url.toLowerCase().startsWith("https://")) {
			String newURL = url.substring(URL_LEN);
			if (newURL.indexOf("/") != -1) {
				hostURL = newURL.substring(0, newURL.indexOf("/"));
				appURL = newURL.substring(newURL.indexOf("/"));
			} else {
				hostURL = newURL;
				appURL = "/";
			}
		} else {
			if (url.indexOf("/") != -1) {
				hostURL = url.substring(0, url.indexOf("/"));
				appURL = url.substring(url.indexOf("/"));
			} else {
				hostURL = url;
				appURL = "/";
			}
		}
	}

	public String processForm( Map<String, String>  map) throws PayException {
		PostMethod post = new PostMethod(url);
		logger.info("url:"+url);
		
		resultInputByte = new String("HttpError").getBytes();
		try {
			URL uRL = new URL(url);
			post.setPath(uRL.getPath());
			post.setContentChunked(true);
			post.setRequestHeader(Constants.CONTENT_TYPE, Constants.APP_FORM_TYPE);
//			NameValuePair[] params = new NameValuePair[1];
//			NameValuePair simcard = new NameValuePair(txnName, new String(txnValue));
//			params[0] = simcard;
			
		    StringBuffer sf = new StringBuffer("");
			String reqstr = "";
			if (null != map && 0 != map.size()) {
				for (Entry<String, String> en : map.entrySet()) {
					try {
						sf.append(en.getKey()
								+ "="
								+ (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
										.encode(en.getValue(), "UTF-8")) + "&");
					} catch (UnsupportedEncodingException e) {
						
						return "";
					}
				}
				reqstr = sf.substring(0, sf.length() - 1);
			}
			
			post.setRequestBody(reqstr);			
			HttpClient httpclient = new HttpClient();
			HttpUtils httpUtils = new HttpUtils();
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(httpUtils.getHttpConnTimeOut()); 
			httpclient.getHttpConnectionManager().getParams().setSoTimeout(httpUtils.getHttpRecvTimeOut());
			httpclient.getHostConfiguration().setHost(hostURL,
					Integer.parseInt(CertificateUnit.getDefaultPort()),
					HttpsParam.getAuthhttps());
			int result = httpclient.executeMethod(post);
			postCharSet = post.getRequestCharSet();
			
			logger.info("HttpClient SSL Execute with POST Method, Get ReturnCode : [" + result + "]");
			String resCode = null;
			String resStr=null;
			if(result == HttpStatus.SC_MOVED_PERMANENTLY || result == HttpStatus.SC_MOVED_TEMPORARILY){
        		logger.info("url has moved, now get new url from location. ");
    			resCode = HttpStatusUnit.getString(String.valueOf(result));
    			
	            // 从头中取出转向的地址
	            Header locationHeader = post.getResponseHeader("location");
	            if (locationHeader != null && (locationHeader.getValue() != null) ) {
	            	String location = uRL.getProtocol() + "://" + uRL.getHost();
	            	if(uRL.getPort() > 0){
	            		location = location + ":" + String.valueOf(uRL.getPort());
	            	}
	            	location = location + locationHeader.getValue();
            		logger.info("url has redirected : " + location);
            		url = location;
//            		resCode = process(txnName, txnValue); //用跳转后的 location url 重新请求。
	            }else{
	    			logger.info("HttpStatusUnit Translate ReturnCode to String = [" + resCode + "]");
					logger.error(HttpStatusUnit.getStatusInfo(result));
	            }
			}else{
				resCode = HttpStatusUnit.getString(String.valueOf(result));
				logger.info("HttpStatusUnit Translate ReturnCode to String = [" + resCode + "]");
				
				if (resCode.equals(Rescode.SUCCESS)) {
					resultInputByte = post.getResponseBody();
					resStr=new String(resultInputByte,"UTF-8");
				} else {
					logger.error(HttpStatusUnit.getStatusInfo(result));
				}
			}
			logger.info("HttpStatusUnit Translate ReturnCode to String = [" + resCode + "]");
			
			//String resCode = HttpStatusUnit.getString(String.valueOf(result));
			//if (resCode.equals(Rescode.SUCCESS)) {				
			//	resultInputByte = post.getResponseBody();
			//} else {
			//	logger.error(HttpStatusUnit.getStatusInfo(result));
			//}
			return resStr;
		} catch (ConnectTimeoutException conex) {
			logger.error("HttpClient ConnectTimeoutException : [" + conex + "]");
			resultInputByte = new String("ConnectTimeout").getBytes();
			return Rescode.COMM_TIMEOUT_ERROR;
		} catch (NoHttpResponseException respex) {
			logger.error("HttpClient NoHttpResponseException : [" + respex + "]");
			resultInputByte = new String("NoHttpResponse").getBytes();
			return Rescode.COMM_NO_RESP_ERROR;
		} catch (IOException ioex) {
			logger.error("HttpClient IOException : [" + ioex + "]");
			resultInputByte = new String("RemoteOutputError").getBytes();
			return Rescode.COMM_ERROR;
		} catch (Exception ex) {
			logger.error("HttpClient process Exception: [" + ex + "]");
			resultInputByte = new String("RemoteUnknownError").getBytes();
			return Rescode.DEFAULT_ERROR;
		} finally {
			post.releaseConnection();
		}
		
	}
	
	public String process(String txnName, byte[] txnValue) throws PayException {
		PostMethod post = new PostMethod(appURL);
		logger.info("url:"+url);
		logger.info("value length:"+txnValue.length);
		resultInputByte = new String("HttpError").getBytes();
		try {
			URL uRL = new URL(url);
			post.setPath(uRL.getPath());
			post.setContentChunked(true);
			post.setRequestHeader(Constants.CONTENT_TYPE, Constants.APP_XML_TYPE);
			NameValuePair[] params = new NameValuePair[1];
			NameValuePair simcard = new NameValuePair(txnName, new String(txnValue));
			params[0] = simcard;
			post.setRequestBody(params);			
			HttpClient httpclient = new HttpClient();
			HttpUtils httpUtils = new HttpUtils();
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(httpUtils.getHttpConnTimeOut()); 
			httpclient.getHttpConnectionManager().getParams().setSoTimeout(httpUtils.getHttpRecvTimeOut());
			httpclient.getHostConfiguration().setHost(hostURL,
					Integer.parseInt(CertificateUnit.getDefaultPort()),
					HttpsParam.getAuthhttps());
			int result = httpclient.executeMethod(post);
			postCharSet = post.getRequestCharSet();
			
			logger.info("HttpClient SSL Execute with POST Method, Get ReturnCode : [" + result + "]");
			String resCode = null;
			if(result == HttpStatus.SC_MOVED_PERMANENTLY || result == HttpStatus.SC_MOVED_TEMPORARILY){
        		logger.info("url has moved, now get new url from location. ");
    			resCode = HttpStatusUnit.getString(String.valueOf(result));
    			
	            // 从头中取出转向的地址
	            Header locationHeader = post.getResponseHeader("location");
	            if (locationHeader != null && (locationHeader.getValue() != null) ) {
	            	String location = uRL.getProtocol() + "://" + uRL.getHost();
	            	if(uRL.getPort() > 0){
	            		location = location + ":" + String.valueOf(uRL.getPort());
	            	}
	            	location = location + locationHeader.getValue();
            		logger.info("url has redirected : " + location);
            		url = location;
            		resCode = process(txnName, txnValue); //用跳转后的 location url 重新请求。
	            }else{
	    			logger.info("HttpStatusUnit Translate ReturnCode to String = [" + resCode + "]");
					logger.error(HttpStatusUnit.getStatusInfo(result));
	            }
			}else{
				resCode = HttpStatusUnit.getString(String.valueOf(result));
				logger.info("HttpStatusUnit Translate ReturnCode to String = [" + resCode + "]");
				
				if (resCode.equals(Rescode.SUCCESS)) {
					resultInputByte = post.getResponseBody();
				} else {
					logger.error(HttpStatusUnit.getStatusInfo(result));
				}
			}
			logger.info("HttpStatusUnit Translate ReturnCode to String = [" + resCode + "]");
			
			//String resCode = HttpStatusUnit.getString(String.valueOf(result));
			//if (resCode.equals(Rescode.SUCCESS)) {				
			//	resultInputByte = post.getResponseBody();
			//} else {
			//	logger.error(HttpStatusUnit.getStatusInfo(result));
			//}
			return resCode;
		} catch (ConnectTimeoutException conex) {
			logger.error("HttpClient ConnectTimeoutException : [" + conex + "]");
			resultInputByte = new String("ConnectTimeout").getBytes();
			return Rescode.COMM_TIMEOUT_ERROR;
		} catch (NoHttpResponseException respex) {
			logger.error("HttpClient NoHttpResponseException : [" + respex + "]");
			resultInputByte = new String("NoHttpResponse").getBytes();
			return Rescode.COMM_NO_RESP_ERROR;
		} catch (IOException ioex) {
			logger.error("HttpClient IOException : [" + ioex + "]");
			resultInputByte = new String("RemoteOutputError").getBytes();
			return Rescode.COMM_ERROR;
		} catch (Exception ex) {
			logger.error("HttpClient process Exception: [" + ex + "]");
			resultInputByte = new String("RemoteUnknownError").getBytes();
			return Rescode.DEFAULT_ERROR;
		} finally {
			post.releaseConnection();
		}
	}

	public InputStream getResultInputStream() {
		return resultInputStream;
	}

	public byte[] getResultInputByte() {
		return resultInputByte;
	}

	public void setResultInputStream(InputStream resultInputStream) {
		this.resultInputStream = resultInputStream;
	}
	
	public String getPostCharSet() {
		return postCharSet;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值