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; }

 

上一篇:python数据库操作


下一篇:在.NET中调用存储过程