Http方式調用WebService,直接發送soap消息到服務端,而後本身解析服務端返回的結果,這種方式比較簡單粗暴,也很好用;soap消息能夠經過SoapUI來生成,也很方便。文中所使用到的軟件版本:Java 1.8.0_19一、HttpClient 4.5.三、Spring 5.1.九、dom4j 2.1.一、jackson 2.9.9。html
參考Java調用WebService方法總結(1)--準備工做java
該方式利用JDK自身提供的API來調用,不須要額外的JAR包。web
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(); } }
利用Apache的HttpClient框架調用。spring
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(); } }
利用Srping的RestTemplate工具調用。apache
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)); }
三種方式其實差很少,主體思想是同樣的就是發送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); } }