package common.util.httpclient.impl;

import common.util.ServletUtils;
import common.util.SysLog;
import common.util.httpclient.HttpClientService;
import common.util.httpclient.HttpRequestContext;
import common.util.httpclient.HttpSendResult;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

public class HttpClientServiceImpl implements HttpClientService {
    private static final SysLog logger = SysLog.getLogger(HttpClientServiceImpl.class);
    private SimpleHttpsClient httpsClient;

    public HttpClientServiceImpl() {
    }

    public HttpSendResult sendRequest(HttpRequestContext requestContext) throws Exception {
        if (requestContext.getHttpMethod().equals("POST")) {
            return StringUtils.isNotBlank(requestContext.getXml()) ? this.postXml(requestContext) : this.postRequest(requestContext);
        } else {
            return this.getRequest(requestContext);
        }
    }

    private HttpSendResult postRequest(HttpRequestContext requestContext) throws Exception {
        logger.logInfo("Post Url=" + requestContext.getUrl());
        if (this.checkSSL(requestContext.getUrl())) {
            return this.httpsClient.postRequest(requestContext.getUrl(), requestContext.getSendParams(), requestContext.getTimeout(), requestContext.getRequestCharset());
        } else {
            HttpSendResult result = new HttpSendResult();
            PostMethod postMethod = new PostMethod(requestContext.getUrl());
            if (!CollectionUtils.isEmpty(requestContext.getReqHeader())) {
                Map<String, String> reqHeader = requestContext.getReqHeader();
                Set<String> keySet = reqHeader.keySet();
                Iterator i$ = keySet.iterator();

                while(i$.hasNext()) {
                    String key = (String)i$.next();
                    postMethod.addRequestHeader(key, (String)reqHeader.get(key));
                }
            }

            NameValuePair[] data = this.createNameValuePair(requestContext.getSendParams());
            postMethod.setRequestBody(data);
            HttpClient client = new HttpClient();
            client.getParams().setSoTimeout(requestContext.getTimeout());
            client.getParams().setParameter("http.protocol.content-charset", requestContext.getRequestCharset());
            InputStream responseBody = null;

            HttpSendResult var18;
            try {
                int status = client.executeMethod(postMethod);
                responseBody = postMethod.getResponseBodyAsStream();
                result.setStatus(status);
                result.setResponseBody(IOUtils.toString(responseBody, requestContext.getResponseCharset()));
                if (status == 301 || status == 302) {
                    Header locationHeader = postMethod.getResponseHeader("location");
                    if (locationHeader != null) {
                        result.setLocation(locationHeader.getValue());
                    }
                }

                var18 = result;
            } catch (Exception var12) {
                logger.logError(var12.getMessage(), var12);
                throw var12;
            } finally {
                postMethod.releaseConnection();
                IOUtils.closeQuietly(responseBody);
            }

            return var18;
        }
    }

    private HttpSendResult postXml(HttpRequestContext requestContext) throws Exception {
        PostMethod postMethod = null;
        InputStream in = null;

        HttpSendResult var17;
        try {
            postMethod = new PostMethod(requestContext.getUrl());
            postMethod.addRequestHeader("Connection", "close");
            if (!CollectionUtils.isEmpty(requestContext.getReqHeader())) {
                Map<String, String> reqHeader = requestContext.getReqHeader();
                Set<String> keySet = reqHeader.keySet();
                Iterator i$ = keySet.iterator();

                while(i$.hasNext()) {
                    String key = (String)i$.next();
                    postMethod.addRequestHeader(key, (String)reqHeader.get(key));
                }
            }

            if (requestContext.getXml() != null) {
                postMethod.setRequestEntity(new StringRequestEntity(requestContext.getXml(), "text/xml", requestContext.getRequestCharset()));
            }

            if (!CollectionUtils.isEmpty(requestContext.getSendParams())) {
                NameValuePair[] nvPairList = this.createNameValuePair(requestContext.getSendParams());
                postMethod.setQueryString(EncodingUtil.formUrlEncode(nvPairList, requestContext.getRequestCharset()));
            }

            HttpClient client = new HttpClient();
            HttpSendResult result = new HttpSendResult();
            HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
            params.setConnectionTimeout(requestContext.getConnectionTimeout());
            params.setSoTimeout(requestContext.getReadTimeout());
            result.setStatus(client.executeMethod(postMethod));
            in = postMethod.getResponseBodyAsStream();
            result.setResponseBody(IOUtils.toString(in, requestContext.getResponseCharset()));
            var17 = result;
        } catch (Exception var11) {
            var11.printStackTrace();
            throw var11;
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }

            if (postMethod != null) {
                postMethod.releaseConnection();
            }

        }

        return var17;
    }

    private HttpSendResult getRequest(HttpRequestContext requestContext) throws Exception {
        if (this.checkSSL(requestContext.getUrl())) {
            String paramString = null;
            if (StringUtils.isNotBlank(requestContext.getGetParamString())) {
                paramString = requestContext.getGetParamString();
            } else if (requestContext.getSendParams() != null && requestContext.getSendParams().size() > 0) {
                paramString = ServletUtils.buildParamString(requestContext.getSendParams());
            }

            return this.httpsClient.getRequest(requestContext.getUrl(), paramString, requestContext.getTimeout(), requestContext.isFollowRedirects());
        } else {
            HttpSendResult result = new HttpSendResult();
            String url = this.appendUrlString(requestContext.getUrl(), requestContext.getGetParamString());
            GetMethod postMethod = new GetMethod(url);
            HttpClient client = new HttpClient();
            client.getParams().setSoTimeout(requestContext.getTimeout());
            InputStream responseBody = null;

            HttpSendResult var8;
            try {
                int status = client.executeMethod(postMethod);
                responseBody = postMethod.getResponseBodyAsStream();
                result.setStatus(status);
                result.setResponseBody(IOUtils.toString(responseBody, requestContext.getResponseCharset()));
                var8 = result;
            } catch (Exception var12) {
                var12.printStackTrace();
                throw var12;
            } finally {
                postMethod.releaseConnection();
                if (responseBody != null) {
                    IOUtils.closeQuietly(responseBody);
                }

            }

            return var8;
        }
    }

    private boolean checkSSL(String url) {
        return url.toUpperCase().startsWith("HTTPS");
    }

    private String appendUrlString(String url, String getParamString) {
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        if (StringUtils.isNotEmpty(getParamString)) {
            if (url.indexOf("?") != -1 && url.indexOf("=") != -1) {
                sb.append("&");
            } else {
                sb.append("?");
            }

            sb.append(getParamString);
        }

        return sb.toString();
    }

    private NameValuePair[] createNameValuePair(Map<String, String> params) {
        if (params == null) {
            return new NameValuePair[0];
        } else {
            NameValuePair[] pairs = new NameValuePair[params.size()];
            int index = 0;

            String key;
            for(Iterator i$ = params.keySet().iterator(); i$.hasNext(); pairs[index++] = new NameValuePair(key, (String)params.get(key))) {
                key = (String)i$.next();
            }

            return pairs;
        }
    }

    public void setHttpsClient(SimpleHttpsClient httpsClient) {
        this.httpsClient = httpsClient;
    }
}
