/**
 * @Author: Kane Wang <wangkane@qq.com>
 * @Date: 2024-04-29 11:09:50
 * @LastEditors: Kane Wang
 * @LastModified: 2025-05-07 22:04:08
 * @FilePath: src/main/java/com/cpic/xim/utils/http/HttpUtils.java
 * @Description: 用于http的相关工具方法
 * 
 *               Copyright (c) 2025 by Kane All rights reserved
 */
package com.cpic.xim.utils.http;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils
{
    /**
     * 
     * @param url
     * @param bodyMap
     * @return
     */
    public static String sendPost( String url, Map<String, String> bodyMap )
    {
        HttpPost post = new HttpPost( url );

        try
        {
            // 创建参数集合
            List<BasicNameValuePair> list = new ArrayList<>();
            // 添加参数
            if ( bodyMap != null )
            {
                for ( String str : bodyMap.keySet() )
                {
                    list.add( new BasicNameValuePair( str, bodyMap.get( str ) ) );
                }
            }
            // 把参数放入请求对象，post发送的参数list，指定格式
            post.setEntity( new UrlEncodedFormEntity( list, "UTF-8" ) );
            CloseableHttpClient client = HttpClients.createDefault();
            // 启动执行请求，并获得返回值
            CloseableHttpResponse response = client.execute( post );
            // 得到返回的entity对象
            HttpEntity entity = response.getEntity();
            // 把实体对象转换为string
            return EntityUtils.toString( entity, "UTF-8" );
        }
        catch ( Exception e1 )
        {
            e1.printStackTrace();
            return "";
        }
    }
}