package com.fjs.scenic.cyt.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class HttpUtil {

    private static final int CONNECTION_TIME = 1000 * 15; //正常设置在5秒：1000 * 5

    /**
     * Describe:
     *
     * @param url
     * @param method
     * @param requestParam
     * @return
     * @throws Exception return:String
     *                   Date:2014-3-24
     * @author:huhaopeng
     */
    public static String httpPost(String url, String method, String requestParam) throws Exception {
        /*System.out.println("-------------------------------------------");
        System.out.println("url:-> " + url);
        System.out.println("method:-> " + method);
        System.out.println("requestParam:-> " + requestParam);
        System.out.println("-------------------------------------------");*/
        String response = "";
        HttpClient client = new HttpClient();
        HttpConnectionManagerParams connectionParams = client.getHttpConnectionManager().getParams();
        connectionParams.setConnectionTimeout(30000); //30秒
        connectionParams.setSoTimeout(120000); //2分钟
        PostMethod postMethod = new UTF8PostMethod(url);

        postMethod.addParameter("Connection", "Keep-Alive");
        postMethod.addParameter("Charset", "UTF-8");
        postMethod.addParameter("Content-Type", "application/x-www-form-urlencoded");
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, CONNECTION_TIME);

        List<Parameter> params = new ArrayList<Parameter>();
        params.add(new Parameter("method", method));
        params.add(new Parameter("requestParam", requestParam));
        postMethod.setRequestBody(buildNameValuePair(params));

        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            response = postMethod.getResponseBodyAsString();
        } else {
            System.out.println("Post Method StatusCode:" + statusCode);
        }
        postMethod.releaseConnection();
        client = null;
        return response;
    }

    /**
     * 封装HttpPost的Name-Value参数对
     *
     * @param list
     * @return
     */
    private static NameValuePair[] buildNameValuePair(List<Parameter> list) {
        int length = list.size();
        NameValuePair[] pais = new NameValuePair[length];
        for (int i = 0; i < length; i++) {
            Parameter param = list.get(i);
            pais[i] = new NameValuePair(param.getName(), param.getValue());
        }
        return pais;
    }
}
