package com.docus.server.report.client;

import com.docus.core.util.Func;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 通过http的方式调用 webservice
 */
public class HttpWsClient {
    private static final Logger logger = LoggerFactory.getLogger(HttpWsClient.class);

    public static String send(String wsdlUrl, Map<String, String> requestProperty, String param) {
        try {
            byte[] paramBytes = param.getBytes(StandardCharsets.UTF_8);
            URL url = new URL(wsdlUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestProperty("Content-Length", String.valueOf(paramBytes.length));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            // 额外的一些请求信息
            if (Func.isNotEmpty(requestProperty)) {
                for (Map.Entry<String, String> entry : requestProperty.entrySet()) {
                    httpConn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setConnectTimeout(60000);
            // 输入内容
            OutputStream outputStream = httpConn.getOutputStream();
            outputStream.write(paramBytes);
            outputStream.flush();
            outputStream.close();
            // 获取返回内容
            InputStreamReader inputStreamReader = new InputStreamReader(httpConn.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                stringBuilder.append(str).append("\n");
            }
            bufferedReader.close();
            inputStreamReader.close();
            return stringBuilder.toString();
        } catch (Exception ex) {
            logger.error("wsdl："+wsdlUrl+", ext requestProperty:"+requestProperty+",  param:"+param,ex);
            return null;
        }
    }

}
