package com.yd.rmi.n22.common.utils;

import com.google.common.base.Strings;
import com.yd.rmi.cache.SystemConstants;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class N22Utils {

    /**
     * 发送请求
     * @param url 接口地址
     * @param requestJson 请求报文
     * @return 响应报文
     */
    public static String postTransaction(String url,String requestJson){
        String responseJson = null;
        if(!Strings.isNullOrEmpty(url) && !Strings.isNullOrEmpty(requestJson)){
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            StringBuilder buffer = new StringBuilder();
            InputStream inputStream;
            BufferedReader reader;
            String line;
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(SystemConstants.COMMON_CONNECTION_TIMEOUT);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(SystemConstants.COMMON_SO_TIMEOUT);
            try{
                postMethod.setDoAuthentication(true);
                postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"GBK");
                postMethod.setRequestHeader("Content_Type","application/json;charset=utf-8");
                postMethod.setRequestHeader("Accept","application/json;charset=utf-8");
                RequestEntity requestEntity = new StringRequestEntity(requestJson,"application/json","UTF-8");
                postMethod.setRequestEntity(requestEntity);
                int statusCode = httpClient.executeMethod(postMethod);
                if(statusCode != HttpStatus.SC_OK){
                    throw new IllegalStateException("transaction method error description :"+postMethod.getStatusLine());
                }
                inputStream = postMethod.getResponseBodyAsStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                while((line = reader.readLine())!= null){
                    buffer.append(line);
                }
                responseJson = buffer.toString();

            }catch(Exception e){
                e.printStackTrace();
            }finally{
                postMethod.releaseConnection();
            }
        }
        return responseJson;
    }
}
