微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java调用webservice请求

基于SOAP协议的WEB服务调用方式:


import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;

/** * webservice请求 * @param xmlStr * @return * @throws Exception */ public static String callXml(String xmlStr, String soapAddress) throws IOException { //地址 URL url = new URL(soapAddress); //调用方法 String soapActionString = ""; logger.info("请求SOAP地址:"+soapAddress); logger.info("请求SOAPAction:"+soapActionString); //打开链接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); logger.info("请求报文:"+xmlStr); //设置好header信息 con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); con.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length)); con.setRequestProperty("SOAPAction", soapActionString); //post请求需要设置 con.setDoOutput(true); con.setDoInput(true); //对请求body 往里写xml 设置请求参数. PrintWriter out = null; byte[] responseData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { out = new PrintWriter(new OutputStreamWriter(con.getoutputStream(),"utf-8")); // 发送请求参数 out.print(xmlStr); out.flush(); //设置响应回来的信息 InputStream ips = con.getInputStream(); byte[] buf = new byte[1024]; int length = 0; while( (length = ips.read(buf)) != -1){ baos.write(buf, 0, length); baos.flush(); } responseData = baos.toByteArray(); } catch (IOException e) { throw new IOException(e); } finally { if (out != null) { out.close(); } try { baos.close(); } catch (IOException e) { throw new IOException(e); } con.disconnect(); } //处理写响应信息 String responseMess = new String(responseData,"utf-8"); responseMess = StringEscapeUtils.unescapeHtml(responseMess); logger.info("响应码:"+con.getResponseCode()); logger.info("响应报文:"+responseMess); return responseMess; }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐