Java调用WebService方法总结(9,end)--Http方式调…
2019-11-20 16:04:01来源:博客园 阅读 ()
Java调用WebService方法总结(9,end)--Http方式调用WebService
Http方式调用WebService,直接发送soap消息到服务端,然后自己解析服务端返回的结果,这种方式比较简单粗暴,也很好用;soap消息可以通过SoapUI来生成,也很方便。文中所使用到的软件版本:Java 1.8.0_191、HttpClient 4.5.3、Spring 5.1.9、dom4j 2.1.1、jackson 2.9.9。
1、准备
参考Java调用WebService方法总结(1)--准备工作
2、调用
2.1、HttpURLConnection方式
该方式利用JDK自身提供的API来调用,不需要额外的JAR包。
public static void httpURLConnection(String soap) { HttpURLConnection connection = null; try { URL url = new URL(urlWsdl); connection = (HttpURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese"); connection.connect(); setBytesToOutputStream(connection.getOutputStream(), soap.getBytes()); byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("httpURLConnection返回soap:" + back); System.out.println("httpURLConnection结果:" + parseResult(back)); } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } }
2.2、HttpClient方式
利用Apache的HttpClient框架调用。
public static void httpClient(String soap) { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(urlWsdl); httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); httpPost.setHeader("SOAPAction", targetNamespace + "toTraditionalChinese"); InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes())); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String back = EntityUtils.toString(responseEntity); System.out.println("httpClient返回soap:" + back); System.out.println("httpClient结果:" + parseResult(back)); } catch (Exception e) { e.printStackTrace(); } }
2.3、RestTemplate方式
利用Srping的RestTemplate工具调用。
public static void restTemplate(String soap) { RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("SOAPAction", targetNamespace + "toTraditionalChinese"); headers.add("Content-Type", "text/xml;charset=UTF-8"); org.springframework.http.HttpEntity<String> entity = new org.springframework.http.HttpEntity<String>(soap, headers); String back = template.postForEntity(urlWsdl, entity, String.class).getBody(); System.out.println("restTemplate返回soap:" + back); System.out.println("restTemplate结果:" + parseResult(back)); }
2.4、小结
三种方式其实差不多,主体思想是一样的就是发送soap报文,就是写法不一样而已。完整例子:
package com.inspur.ws; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.springframework.http.HttpHeaders; import org.springframework.web.client.RestTemplate; /** * Http方式调用WebService * */ public class Http { private static String urlWsdl = "http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl"; private static String targetNamespace = "http://webxml.com.cn/"; /** * HttpURLConnection方式 * @param soap */ public static void httpURLConnection(String soap) { HttpURLConnection connection = null; try { URL url = new URL(urlWsdl); connection = (HttpURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese"); connection.connect(); setBytesToOutputStream(connection.getOutputStream(), soap.getBytes()); byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("httpURLConnection返回soap:" + back); System.out.println("httpURLConnection结果:" + parseResult(back)); } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } } /** * HttpClient方式 * @param soap */ public static void httpClient(String soap) { try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(urlWsdl); httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); httpPost.setHeader("SOAPAction", targetNamespace + "toTraditionalChinese"); InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes())); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); String back = EntityUtils.toString(responseEntity); System.out.println("httpClient返回soap:" + back); System.out.println("httpClient结果:" + parseResult(back)); } catch (Exception e) { e.printStackTrace(); } } /** * RestTemplate方式 * @param soap */ public static void restTemplate(String soap) { RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("SOAPAction", targetNamespace + "toTraditionalChinese"); headers.add("Content-Type", "text/xml;charset=UTF-8"); org.springframework.http.HttpEntity<String> entity = new org.springframework.http.HttpEntity<String>(soap, headers); String back = template.postForEntity(urlWsdl, entity, String.class).getBody(); System.out.println("restTemplate返回soap:" + back); System.out.println("restTemplate结果:" + parseResult(back)); } /** * 从输入流获取数据 * @param in * @return * @throws IOException */ private static byte[] getBytesFromInputStream(InputStream in) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len; while ((len = in.read(b)) != -1) { baos.write(b, 0, len); } byte[] bytes = baos.toByteArray(); baos.close(); in.close(); return bytes; } /** * 向输入流发送数据 * @param out * @param bytes * @throws IOException */ private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); byte[] b = new byte[1024]; int len; while ((len = bais.read(b)) != -1) { out.write(b, 0, len); } out.flush(); out.close(); bais.close(); } /** * 解析结果 * @param s * @return */ private static String parseResult(String s) { String result = ""; try { Reader file = new StringReader(s); SAXReader reader = new SAXReader(); Map<String, String> map = new HashMap<String, String>(); map.put("ns", "http://webxml.com.cn/"); reader.getDocumentFactory().setXPathNamespaceURIs(map); Document dc = reader.read(file); result = dc.selectSingleNode("//ns:toTraditionalChineseResult").getText().trim(); } catch (Exception e) { e.printStackTrace(); } return result; } public static void main(String[] args) { String soap11 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webxml.com.cn/\">" + "<soapenv:Header/>" + "<soapenv:Body>" + "<web:toTraditionalChinese>" + "<web:sText>小学</web:sText>" + "</web:toTraditionalChinese>" + "</soapenv:Body>" + "</soapenv:Envelope>"; String soap12 = "<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:web=\"http://webxml.com.cn/\">" + "<soapenv:Header/>" + "<soapenv:Body>" + "<web:toTraditionalChinese>" + "<web:sText>大学</web:sText>" + "</web:toTraditionalChinese>" + "</soapenv:Body>" + "</soapenv:Envelope>"; httpURLConnection(soap11); httpURLConnection(soap12); httpClient(soap11); httpClient(soap12); restTemplate(soap11); restTemplate(soap12); } }View Code
原文链接:https://www.cnblogs.com/wuyongyin/p/11899184.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- 国外程序员整理的Java资源大全(全部是干货) 2020-06-12
- 2020年深圳中国平安各部门Java中级面试真题合集(附答案) 2020-06-11
- 2020年java就业前景 2020-06-11
- 04.Java基础语法 2020-06-11
- Java--反射(框架设计的灵魂)案例 2020-06-11
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash