package com.steerinfo.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpRequest {
    /**
     * @MethodName: postJsonMethodParamsEncode
     * @Description x-www-form-urlencoded格式-map格式-请求
     * @Author fubo
     * @Date 2020/8/28 19:10
     **/
    public static String postJsonMethodParamsEncode(String postURL, Map<String,String> destMap){
        try {
            PostMethod postMethod = null;
            postMethod = new PostMethod(postURL) ;
            postMethod.setRequestHeader("Content-Type", "application/application/json;charset=utf-8") ;
            NameValuePair[] data = new NameValuePair[destMap.size()];
            int i = 0;
            for (String key : destMap.keySet()){
                data[i] = new NameValuePair(key,destMap.get(key));
                i++;
            }

            postMethod.setRequestBody(data);
            HttpClient httpClient = new HttpClient();
            int response = httpClient.executeMethod(postMethod);
            return postMethod.getResponseBodyAsString() ;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 传输json串的post接口
     * @param postURL
     * @param destMap
     * @return
     */
    public static String postJsonMethodEncode(String postURL, Map<String,String> destMap){
        try {
            PostMethod postMethod = null;
            postMethod = new PostMethod(postURL) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            NameValuePair[] data = new NameValuePair[destMap.size()];
            int i = 0;
            for (String key : destMap.keySet()){
                data[i] = new NameValuePair(key,destMap.get(key));
                i++;
            }

            postMethod.setRequestBody(data);
            HttpClient httpClient = new HttpClient();
            int response = httpClient.executeMethod(postMethod);
            return postMethod.getResponseBodyAsString() ;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * @MethodName: postmancookie
     * @Description 携带accessToken请求
     * @Author fubo
     * @Date 2020/12/21 10:02
     **/
    public static String postmanAccessToken(String requestUrl,String params,String accessToken) {
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(requestUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("authorization",accessToken); // 设置accessToken
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            if (connection != null) {
                InputStream inputStream = null;
                //根据responseCode来获取输入流，此处错误响应码的响应体内容也要获取（看服务端的返回结果形式决定）
                if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                    inputStream = connection.getInputStream();
                } else {
                    inputStream = connection.getErrorStream();
                }
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\r\n");
                }
                br.close();
            }
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
