/*
 * @Author: Kane
 * @Date: 2022-04-22 09:54:05
 * @LastEditors: Kane
 * @LastEditTime: 2022-04-22 16:18:17
 * @FilePath: \DisasterWarning\src\main\java\com\cpic\xim\httpUtil\HttpUtils.java
 * @Description: http相关的工具类。
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
package com.cpic.xim.httpUtil;

import java.util.HashMap;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;

/**
 * Http相关的工具类。
 */
public class HttpUtils
{
    /**
     * 以POST方式发送http请求！
     * @param url 访问的链接字符串
     * @param headers 请求头部参数集合
     * @param params 请求体字符串
     */
    public static String postHttpRequest( String url, HashMap<String, String> headers,
            String param ) throws MalformedURLException
    {
        URL httpURL = null;
        HttpURLConnection conn = null;
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();

        try
        {
            // 获取connection
            httpURL = new URL( url );
            conn = (HttpURLConnection) httpURL.openConnection();

            // 设置请求方式
            conn.setRequestMethod( "POST" );

            // 设置请求头参数
            for ( HashMap.Entry<String, String> head : headers.entrySet())
            {
                String key = head.getKey();

                conn.setRequestProperty( head.getKey(), head.getValue() );
            }

            // 连接
            conn.setDoInput( true );
            conn.setDoOutput( true );
            conn.connect();

            // 输出请求
            out = new OutputStreamWriter( conn.getOutputStream(), StandardCharsets.UTF_8 );
            out.write( param );
            out.flush();

            // 读取返回值。
            in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );

            String line = in.readLine();

            while (line != null)
            {
                result.append( line );

                line = in.readLine();
            }
        }
        catch (IOException error)
        {

        }
        finally
        {
            try
            {
                if ( out != null)
                {
                    out.close();
                }

                if ( in != null)
                {
                    in.close();
                }

                if ( conn != null)
                {
                    conn.disconnect();
                }
            }
            catch (Exception error)
            {
                error.printStackTrace();
            }
        }

        return result.toString();
    }
}
