package com.chinacreator.video.util;

import net.sf.json.JSONObject;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author zhengrong.yan
 * @date 2021/5/10 14:02
 */
public class HttpUtils {
    public static String post(String href, JSONObject data) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(href);
            if (data != null) {
                // 添加请求参数
                for(Object str:data.keySet()){
                    uriBuilder.addParameter((str.toString()), data.get(str).toString());
                }
            }
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "";
    }
}
