package com.microframework.okr.core.ws;
import org.apache.cxf.helpers.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* SoapHttp client 请求PS Web service 接口
*
* @author <a href="mailto:fshuaxm@vip.qq.com">fshuaxm</a>
* @date 2018/11/6
* @see
* @since JDK1.8
*/
public class SoapHttpSubmit {
/**
* 日志对象
*/
private static Logger logger = LoggerFactory.getLogger(SoapHttpSubmit.class.getName());
/**
* 调用webservice超时 毫秒
*/
private static int timeout = 180000;
/**
* 编码
*/
private static String encoding = "UTF-8";
/***************************************************************************
* 模拟远程Http请求Webservice接口
*
* @param soapHeader_Bytes byte[] 请求参数二进制
* @param soapAction webservice 服务SOAPAction
* @param host webservice 服务host
* @param serverAddress webservice 服务地址
* @return
*/
public static String buildRequest(byte[] soapHeader_Bytes, String soapAction, String host, String serverAddress) throws Exception {
String responseString = null;
URL url = new URL(serverAddress);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try {
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(timeout));
System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(timeout));
con.setReadTimeout(timeout);
con.setConnectTimeout(timeout);
// Assert.isNull(con, "Http Connection is Null");
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("SOAPAction", soapAction);
con.setRequestProperty("Host", host);
con.setRequestProperty("Accept-Encoding", "gzip,deflate");
con.addRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
con.setRequestProperty("Content-type", "text/xml;charset=UTF-8");
// con.setRequestProperty("Content-type", "application/soap+xml; charset=utf-8");
con.setAllowUserInteraction(true);
con.connect();
OutputStream output = con.getOutputStream();
output.write(soapHeader_Bytes);
output.flush();
output.close();
InputStream input = con.getInputStream();
try {
responseString = IOUtils.toString(input, encoding);
input.close();
logger.info("HTTP response:{}", responseString);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
} catch (ProtocolException ex) {
logger.error("The Http connection UNSupport the Post method.", ex);
throw new Exception(ex);
} catch (IOException ex) {
InputStream is = con.getErrorStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader in = new BufferedReader(isr);
String inputLine;
// The location where the results are stored
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("result.xml")));
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
bw.write(inputLine);
bw.newLine();
bw.close();
}
in.close();
logger.error("The Http connection Stream error,", ex);
throw new Exception(ex);
} catch (Exception ex) {
logger.error("The Http other error,", ex);
throw new Exception(ex);
}
return responseString;
}
public static String buildKMRequest(byte[] soapBody_bytes, String webservice_url) {
String responseStr = "";
//WebService服务地址
HttpURLConnection conn;
try {
URL wsUrl = new URL(webservice_url);
conn = (HttpURLConnection) wsUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
OutputStream os = conn.getOutputStream();
os.write(soapBody_bytes);
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
String ss = new String(b, 0, len, encoding);
responseStr += ss;
}
logger.info("Km SoapHttpRequest response", responseStr);
is.close();
os.close();
conn.disconnect();
} catch (MalformedURLException e) {
logger.error("1. The URL protocol, format or path error, to check the code in your applicationIf it is a path problem, it is best not to contain Chinese path, because sometimes Chinese path is garbled, lead to can't identify. \n " +
"2. The problem of the jar: use jdom to parse the XML file, if the path contains gnujaxp. Jars, jdom willCall it to parse the XML file, lead to the emergence of the abnormal.", e);
} catch (IOException e) {
logger.error("The Http connection Stream error,", e);
throw new RuntimeException(e);
}
return responseStr;
}
public static String buildRequest(String soapHeader, String soapAction, String host, String serverAddress) throws Exception {
if (soapHeader != null) {
long from = System.currentTimeMillis();
logger.info("{} buildRequest {} soapAction={} input={}", from, serverAddress, soapAction, soapHeader);
byte[] soapHeader_Bytes = soapHeader.getBytes();
String responseString = buildRequest(soapHeader_Bytes, soapAction, host, serverAddress);
long to = System.currentTimeMillis();
logger.info("{} buildRequest {} soapAction={} cost times {} output={}", to, serverAddress, soapAction, (to - from), responseString);
return responseString;
}
return null;
}
// public static void main(String[] args) throws MalformedURLException {
// String json_string = "{\"root\":{\"requestdata\":{\"transaction_nbr\":978,\"approver_id\":\"195041\",\"comments\":\"已经不适合现在岗位工作\",\"approve_action\":\"A\"}}}";
//
// // 拼装soap请求报文
// StringBuilder soapHeader = new StringBuilder();
// // 修改点
// soapHeader.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:b=\"http://xmlns.oracle.com/Enterprise/Tools/schemas/B_WFL_APR_REQ.V1\">\n");
// soapHeader.append(" <soapenv:Header xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n");
// soapHeader.append(" <wsse:Security soap:mustUnderstand=\"1\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\n");
// soapHeader.append(" <wsse:UsernameToken wsu:Id=\"UsernameToken-1\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n");
// soapHeader.append(" <wsse:Username>WECHAT_INTF</wsse:Username>\n");
// soapHeader.append(" <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">1</wsse:Password>\n");
// soapHeader.append(" </wsse:UsernameToken>\n");
// soapHeader.append(" </wsse:Security>\n");
// soapHeader.append(" </soapenv:Header>\n");
// soapHeader.append(" <soapenv:Body>\n");
// // 修改点
// soapHeader.append(" <b:B_INTF_REQUEST>\n");
// soapHeader.append(" <b:json_string>\n");
// soapHeader.append(json_string).append("</b:json_string>\n");
// soapHeader.append(" </b:B_INTF_REQUEST>\n");
// soapHeader.append(" </soapenv:Body>\n");
// soapHeader.append("</soapenv:Envelope>");
//
// // webservice 服务SOAPAction
// String soapAction = "WflApr.v1";
// // webservice 服务host
// String host = "192.168.210.20:8000";
// /**
// * webservice 服务url
// */
// String serverAddress = "http://192.168.210.20:8000/PSIGW/PeopleSoftServiceListeningConnector/PSFT_HR/B_WFL_APR.1.wsdl";
//
// String resp_string = null;
// try {
// resp_string = SoapHttpSubmit.buildRequest(soapHeader.toString().getBytes(), soapAction, host, serverAddress);
// } catch (Exception e) {
// e.printStackTrace();
// }
// System.out.println(resp_string);
// }
}