package com.pine.admin.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * com.lecshop.util
 *
 * @author Pine
 * @email 771190883@qq.com
 * @date 2019/11/8
 */
@Slf4j
public class PostUtil {

    public static JSONObject sendRequest(String strReqJsonStr, String getUrl) {
        log.debug(" sendRequest start , the strReqJsonStr is : {}  ,getUrl :{}", strReqJsonStr, getUrl);
        HttpURLConnection httpURLConnection = null;
        BufferedReader in = null;
        PrintWriter out = null;
        String resultStr = null;
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            URL url = new URL(getUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content_Type", "application/json");
            httpURLConnection.setRequestProperty("Accept_Charset", "UTF-8");
            httpURLConnection.setRequestProperty("contentType", "UTF-8");
            //发送POST请求参数
            out = new PrintWriter(httpURLConnection.getOutputStream());
            out.write(strReqJsonStr);
            out.flush();
            //读取响应
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = null;
                in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                log.debug(" sendRequest result is : {} ", content.toString());
                //转换成json对象
                JSONObject respJson = JSON.parseObject(content.toString());
                return respJson;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("errCode", "HttpURLException");
            resultMap.put("msg", "调用出现异常：" + e.toString());
            resultStr = JSONObject.toJSONString(resultMap);
            log.error("  sendRequest error , the resultStr : {} ,getUrl :{} ", resultStr,getUrl);
        } finally {
            if (out != null) {
                out.close();
            }
            httpURLConnection.disconnect();
        }
        return null;
    }
}
