package cn.com.ty.lift.business.common.http;

import com.google.gson.Gson;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author xp-zhao@logictech.cn
 * @CreateOn 2016/11/01^ 16:34
 * @Remark Http公共底层类
 */
public class HttpBasic {

    public static final Gson gson = new Gson();

    public static final String GET = "GET";

    public static final String POST = "POST";

    //application/x-www-form-urlencoded
    public static String contentType = "application/json;charset=utf-8";

    public static String getContentType() {
        return contentType;
    }

    /**
     * @Author xp-zhao@logictech.cn
     * @CreateOn 2016/8/31 12:48
     * @Remark Map转换成URL参数拼接格式
     */
    public static String buildParameters(Map<String, Object> map) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("&");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            try {
                if (entry.getValue() instanceof String[]) buffer.append(entry.getKey() + "=" + URLEncoder.encode(((String[]) entry.getValue())[0], "UTF-8"));
                else buffer.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8") + "");
            } catch (Exception e) {
                continue;
            }
            buffer.append("&");
        }
        return buffer.toString().replaceAll("&$", "");
    }


    /**
     * @Author xp-zhao@logictech.cn
     * @CreateOn 2016/8/31 12:49
     * @Remark 转换Map<String,Object>为Map<String,String>
     */
    public static Map<String, String> convertMapValueObject2String(Map<String, ?> convert) {
        Map<String, String> newMap = new HashMap<>();
        if (convert != null)
            for (Map.Entry<String, ?> entry : convert.entrySet()) {
                if (entry.getValue() instanceof String) {
                    newMap.put(entry.getKey(), (String) entry.getValue());
                } else newMap.put(entry.getKey(), Objects.toString(entry.getValue()));
            }
        return newMap;

    }

}
