package com.prolog.eis.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpUtil {

    private static String charset = "utf-8";

    public static String postMethod(String url, String json) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(url);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(60000 * 5)
                .setConnectTimeout(60000 * 5).setConnectionRequestTimeout(60000 * 5)
                .setStaleConnectionCheckEnabled(true).build();
        httpPost.setConfig(defaultRequestConfig);
        CloseableHttpClient client = HttpClients.createDefault();
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(json, charset);
        entity.setContentEncoding(charset);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = response.getEntity();
            return EntityUtils.toString(httpEntity, charset);
        }
        return null;
    }

}
