package com.seeyon.apps.src_automatic.util;

import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

public class WebServiceUtil {

	public static String invoke(String  postUrl, String soapXml, String action) throws Exception {
		// 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        //  设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(60000)
                .setConnectTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        String retStr;
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", action);
            StringEntity data = new StringEntity(soapXml.toString(),
                    Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            response = closeableHttpClient
                    .execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
                try {
                    Document doc = DocumentHelper.parseText(retStr);
                    retStr = doc.getRootElement().getStringValue();
                } catch (Exception e) {
                	throw new Exception("解析xml报文失败：" + (retStr.length() > 50 ?  retStr.substring(0,50) : retStr));
                }
        		return retStr;
            } else {
            	throw new Exception("未获取到数据！");
            }
        } catch(Exception e) {
        	throw e;
        } finally {
        	try {
        		// 释放资源
        		if(null != response) {
        			response.close();
        		}
        		if(null != closeableHttpClient) {
        			closeableHttpClient.close();
        		}
        	} catch(Exception e) {}
        }
        
	}
	
}
