package com.ghy.order.utils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类 - 用于阿里云API调用
 * 参考：https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
 */
public class HttpUtils {
    
    /**
     * 发送GET请求
     *
     * @param host    主机地址
     * @param path    路径
     * @param method  请求方法
     * @param headers 请求头
     * @param querys  查询参数
     * @return HttpResponse
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method,
                                   Map<String, String> headers,
                                   Map<String, String> querys) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }
    
    /**
     * 发送POST请求
     *
     * @param host    主机地址
     * @param path    路径
     * @param method  请求方法
     * @param headers 请求头
     * @param querys  查询参数
     * @param bodys   请求体
     * @return HttpResponse
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                    Map<String, String> headers,
                                    Map<String, String> querys,
                                    Map<String, String> bodys) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            
            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }
        
        return httpClient.execute(request);
    }
    
    /**
     * 构建URL
     *
     * @param host   主机地址
     * @param path   路径
     * @param querys 查询参数
     * @return 完整URL
     */
    private static String buildUrl(String host, String path, Map<String, String> querys) throws Exception {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (path != null && path.length() > 0) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (query.getKey() != null && query.getKey().length() > 0) {
                    sbQuery.append(query.getKey());
                }
                if (query.getValue() != null && query.getValue().length() > 0) {
                    sbQuery.append("=").append(URLEncoder.encode(query.getValue(), "utf-8"));
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        
        return sbUrl.toString();
    }
} 