package com.xt.hb.gis.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

@SuppressWarnings("deprecation")
public class HttpProxy {
    private final static int TIMEOUT_CONNECTION = 5000;
    private final static int TIMEOUT_SOCKET = 5000;

    public static String _MakeURL(String p_url, Map<String, Object> params) {
        StringBuilder url = new StringBuilder(p_url);
        if (url.indexOf("?") < 0) url.append('?');

        if (params != null) {
            for (String name : params.keySet()) {
                url.append('&');
                url.append(name);
                url.append('=');
                url.append(String.valueOf(params.get(name)));
            }
        }
        return url.toString().replace("?&", "?");
    }

    /**
     * get请求URL
     *
     * @param url
     */
    protected static InputStream http_get_inputStream(String url) throws Exception {
        String responseBody = http_get_json(url);
        return new ByteArrayInputStream(responseBody.getBytes());
    }

    /**
     * get请求URL
     *
     * @param url
     */
    protected static InputStream http_get_inputStream(String url, Map<String, Object> params) throws Exception {
        String responseBody = http_get_json(url, params);
        return new ByteArrayInputStream(responseBody.getBytes());
    }

    /**
     * post请求URL
     *
     * @param url
     * @param params
     * @return
     */
    protected static InputStream http_post_inputstream(String url, Map<String, Object> params) throws Exception {

        String response = http_post_json(url, params);
        return new ByteArrayInputStream(response.getBytes());
    }

    /**
     * get请求URL 返回Json格式数据
     *
     * @param path
     * @return
     */
    public static String http_get_json(String path) throws IOException {
        //logger.info(path);
        // 新建HttpGet对象
        HttpGet httpGet = new HttpGet(path);
        return invoke(httpGet);
    }

    private static DefaultHttpClient getHttpClient() {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION); // 设置连接超时
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET); // 设置请求超时
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(params);

        return defaultHttpClient;
    }

    public static String http_get_json(String path, Map<String, Object> params) throws IOException {
        String urls = _MakeURL(path, params);
        return http_get_json(urls);
    }

    /**
     * 公用post方法
     *
     * @param path
     * @param params
     * @return
     */
    public static String http_post_json(String path, List<NameValuePair> params) {
        try {
            //            logger.info(path);
            // 新建HttpPost对象
            HttpPost httpPost = new HttpPost(path);
            HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            // 设置参数实体
            httpPost.setEntity(entity);

            return invoke(httpPost);
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected static String http_post_json(String path, Map<String, Object> params) {
        return http_post_json(path, postParams(params));
    }

    private static String invoke(HttpPost httppost) {
        try {
            // 获取HttpClient对象
            DefaultHttpClient httpclient = getHttpClient();
            HttpResponse response = httpclient.execute(httppost);
            return responseParams(response);
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        }
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String invoke(HttpGet httpget) throws IOException {
        // 获取HttpClient对象
        DefaultHttpClient httpclient = getHttpClient();
        HttpResponse response = httpclient.execute(httpget);
        return responseParams(response);

    }

    private static String responseParams(HttpResponse response) throws IOException {
        // 判断是够请求成功
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取返回的数据
            //				System.out.println("Response Status: "
            //						+ response.getStatusLine() + "--数据请求成功");
            return CustomGetMethod.getGzip(response);
        }
        return null;

    }

    private static List<NameValuePair> postParams(Map<String, Object> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }

        return nvps;
    }

    protected static InputStream getNetFile(String urlStr) {
        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();// 打开连接
            return con.getInputStream();// 输入流
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
