/**
 * 
 */
package cn.newfeifan.mall.module.pay.fuiou.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import cn.newfeifan.mall.framework.common.exception.ErrorCode;
import lombok.Setter;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;


/**
 * @author Administrator
 * 
 */
@Setter
public class FuiouHttpPoster {

	public FuiouHttpPoster() {
	}

	private String url;

	private String charset;

	public FuiouHttpPoster(String url, String charset) {
		super();
		this.url = url;
		this.charset = charset;
	}

	public FuiouHttpPoster(String url) {
		super();
		this.url = url;
		this.charset = Charset.defaultCharset().name();
	}

	
	
	public String newPost(final String body) throws Exception {
		return post(new PostMethodCallback() {

			@Override
			public void doInPostMethod(PostMethod postMethod) {

				try {
					postMethod.setRequestEntity(new StringRequestEntity(body,"application/json","UTF-8"));
				} catch (UnsupportedEncodingException e) {
					ErrorCode err = new ErrorCode(1, e.getMessage());
					throw exception(err);
				}
			}
		});
	}
	
	

	/**
	 * 使用http协议发送xmltext到url
//	 *
//	 * @param url
//	 *            将要发送的地址
//	 * @param xmltext
//	 *            将要发送的内容
//	 * @return http返回码
//	 * @throws LoanException
//	 * @throws Exception
	 */
	private String post(PostMethodCallback callback) throws Exception {
		PostMethod xmlpost = null;
		HttpClient httpclient = new HttpClient();
		try {
			// https设置
			if (url.indexOf("https://") != -1) {
				// 创建SSL连接
				@SuppressWarnings("deprecation")
				Protocol myhttps = new Protocol("https",
						new MySSLSocketFactory(), 443);
				Protocol.registerProtocol("https", myhttps);
			}	
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
			httpclient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
			xmlpost = new PostMethod(url);
			httpclient.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
			httpclient.getParams().setContentCharset(charset);
			// xmlpost.setRequestHeader("content-type", "text/xml; charset=" +
			// charset);

			// 内部回调，发送数据，设置参数用
			callback.doInPostMethod(xmlpost);
			// 执行请求
			httpclient.executeMethod(xmlpost);

			// 获取返回信息
			InputStream ips = xmlpost.getResponseBodyAsStream();
			List<Byte> byteList = new ArrayList<Byte>();

			int is = 0;
			while ((is = ips.read()) != -1)
				byteList.add((byte) is);

			byte[] allb = new byte[byteList.size()];
			for (int j = 0; j < byteList.size(); j++)
				allb[j] = byteList.get(j);
			String responseString = new String(allb, charset);
			// LogWriter.debug(this, "HTTP返回码=" + responseStatCode);
			System.out.println("应答数据=" + responseString);

			if (url.indexOf("https://") != -1)
				Protocol.unregisterProtocol("https");
			return responseString;
		} catch (IOException ex2) {
			ErrorCode err = new ErrorCode(1, ex2.getMessage());
//			throw exception(err);
//			System.out.println("报文发送到[" + url + "]失败:" + ex2.getMessage());
//			throw new Exception("报文发送异常");
		} catch (Exception ex) {
			ErrorCode err = new ErrorCode(1, ex.getMessage());
			throw exception(err);
//			System.out.println("报文发送到[" + url + "]失败:" + ex.getMessage());
//			throw new Exception("报文发送异常");
		} finally {
			try {
				if(xmlpost != null)
					xmlpost.releaseConnection();
				if(httpclient != null)
					httpclient.getHttpConnectionManager().closeIdleConnections(0);
			} catch (Exception e) {
				ErrorCode err = new ErrorCode(1, e.getMessage());
				throw exception(err);
			}
		}

		return null;
	}

	/**
	 * PostMethod回调处理
	 * 
	 */
	public interface PostMethodCallback {
		public void doInPostMethod(PostMethod postMethod);
	}

}
