赞
踩
WebService工具类:
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import lombok.extern.slf4j.Slf4j; @Slf4j public class WebServiceUtil { public static String requestXML(String wsUrl,String params) { URL url = null; HttpURLConnection con = null; InputStream resultIS = null; try { //下面这行代码是用字符串拼出要发送的xml,xml的内容是从测试软件里拷贝出来的 //需要注意的是,有些空格不要弄丢哦,要不然会报500错误的。 //参数什么的,你可以封装一下方法,自动生成对应的xml脚本 String soap = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.ucstar.qflag\">" + "<soapenv:Header/>" + "<soapenv:Body>" + "<web:requestXMLData soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<_requestData xsi:type=\"xsd:string\"><![CDATA[" + params + "]]></_requestData>" + "</web:requestXMLData>" + "</soapenv:Body>" + "</soapenv:Envelope>"; log.info("请求webservice: {}, {}", wsUrl, soap); url = new URL(wsUrl); con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); con.setRequestProperty("SOAPAction", ""); // 通过流的方式将请求体发送出去: OutputStream out = con.getOutputStream(); out.write(soap.getBytes()); out.close(); // 服务端返回正常: int code = con.getResponseCode(); if (code == 200) {// 服务端返回正常 resultIS = con.getInputStream(); } else { log.error("调用失败:{}", code); resultIS = con.getErrorStream(); } byte[] b = new byte[1024]; StringBuffer sb = new StringBuffer(); int len = 0; while ((len = resultIS.read(b)) != -1) { String str = new String(b, 0, len, "UTF-8"); sb.append(str); } log.info("返回结果:{}", sb.toString()); return sb.toString(); } catch (Exception e) { log.error("", e); } finally { if(resultIS != null) { try { resultIS.close(); } catch (IOException e) { log.error("", e); } } if(con != null) { con.disconnect(); } } return null; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。