java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Idea调用WebService

Idea调用WebService的关键步骤和注意事项

作者:A.不愿起名字的人

这篇文章主要介绍了如何在Idea中调用WebService,包括理解WebService的基本概念、获取WSDL文件、阅读和理解WSDL文件、选择对接测试工具或方式、发送请求和接收响应、处理响应结果以及错误处理,需要的朋友可以参考下

前言

​ WebService是一种基于网络的技术,它允许不同的应用程序在互联网上相互通信。要进行WebService对接,以下是一些关键步骤和注意事项:

一、理解WebService的基本概念

二、获取WSDL文件

三、阅读和理解WSDL文件

四、选择对接测试工具或方式

五、发送请求和接收响应

六、直接通过xml和http请求访问

​ 1. 引用包

        <!--
             使用apache的httpclient发送http,需要引入httpclient依赖;
             使用OMElement需要引入axis2-transport-http依赖;改以来本身带有httpclient依赖,所以
                 我们不在需要单独引入httpclient依赖了
         -->
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-transport-http</artifactId>
            <version>1.7.8</version>
        </dependency>

​ 2.

package com.smart.util;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AbcAxis2DemoApplicationUtils {
	public static String doPost(String partNo) throws  IOException {
		// webservice的wsdl地址
		final String wsdlURL = ""
		// 设置编码。(因为是直接传的xml,所以我们设置为text/xml;charset=utf8)
		final String contentType = "text/xml;charset=utf8";
		/// 拼接要传递的xml数据(注意:此xml数据的模板我们根据wsdlURL从SoapUI中获得,只需要修改对应的变量值即可)
		StringBuffer xMLcontent = new StringBuffer("");
		xMLcontent.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:DefaultNamespace\">\n");
		xMLcontent.append("   <soapenv:Header/>\n");
		xMLcontent.append("   <soapenv:Body>\n");
		xMLcontent.append("     <urn:字段1>Shanghai</urn:字段1>\n");
		xMLcontent.append("     <urn:字段2>" + "TAN2921" + "</urn:字段2>\n");
		xMLcontent.append("   </soapenv:Body>\n");
		xMLcontent.append("</soapenv:Envelope>");

		// 调用工具类方法发送http请求
		String responseXML = HttpSendUtil.doHttpPostByHttpClient(wsdlURL, contentType, xMLcontent.toString());
		// 当然我们也可以调用这个工具类方法发送http请求
		// String responseXML = HttpSendUtil.doHttpPostByRestTemplate(wsdlURL, contentType, xMLcontent.toString());

		// 利用axis2的OMElement,将xml数据转换为OMElement
		OMElement omElement = OMXMLBuilderFactory
				.createOMBuilder(new ByteArrayInputStream(responseXML.getBytes()), "utf-8").getDocumentElement();
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(true); // 设置为true以处理命名空间
			DocumentBuilder builder = factory.newDocumentBuilder();
			InputSource inputSource = new InputSource(new StringReader(responseXML));
			Document document = builder.parse(inputSource);

			// 获取所有名为"OUTPUT_SHIPTOPARTYReturn"的元素,并考虑命名空间
			NodeList nodeList = document.getElementsByTagNameNS("urn:DefaultNamespace", "OUTPUT_SHIPTOPARTYReturn");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Element element = (Element) nodeList.item(i);
				// 检查元素是否有文本内容(即非空且非自闭合标签)
				if (element.hasChildNodes() && element.getFirstChild().getNodeType() == Node.TEXT_NODE) {
					String textContent = element.getTextContent();
					System.out.println("Extracted value: " + textContent);
					return textContent;
				}
			}

		} catch (ParserConfigurationException | SAXException | IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String getNodeValue(Document document, String nodePaht) {
		XPathFactory xpfactory = XPathFactory.newInstance();
		XPath path = xpfactory.newXPath();
		String servInitrBrch = "";
		try {
			servInitrBrch = path.evaluate(nodePaht, document);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return servInitrBrch;
	}



	public static Document StringTOXml(String str) {

		StringBuilder sXML = new StringBuilder();
		sXML.append(str);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		try {
			InputStream is = new ByteArrayInputStream(sXML.toString().getBytes("utf-8"));
			doc = dbf.newDocumentBuilder().parse(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}
}
/**
 * HTTP工具类
 *
 * @author JustryDeng
 * @DATE 2018年9月22日 下午10:29:08
 */
class HttpSendUtil {

	/**
	 * 使用apache的HttpClient发送http
	 *
	 * @param wsdlURL
	 *            请求URL
	 * @param contentType
	 *            如:application/json;charset=utf8
	 * @param content
	 *            数据内容
	 * @DATE 2018年9月22日 下午10:29:17
	 */
	static String doHttpPostByHttpClient(final String wsdlURL, final String contentType, final String content)
			throws ClientProtocolException, IOException {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		HttpPost httpPost = new HttpPost(wsdlURL);
		StringEntity entity = new StringEntity(content.toString(), "UTF-8");
		// 将数据放入entity中
		httpPost.setEntity(entity);
		httpPost.setHeader("Content-Type", contentType);
		// 响应模型
		CloseableHttpResponse response = null;
		String result = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			// 注意:和doHttpPostByRestTemplate方法用的不是同一个HttpEntity
			org.apache.http.HttpEntity responseEntity = response.getEntity();
			System.out.println("响应ContentType为:" + responseEntity.getContentType());
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity);
				System.out.println("响应内容为:" + result);
			}
		} finally {
			// 释放资源
			if (httpClient != null) {
				httpClient.close();
			}
			if (response != null) {
				response.close();
			}
		}
		return result;
	}

	/**
	 * 使用springframework的RestTemplate发送http
	 *
	 * @param wsdlURL
	 *            请求URL
	 * @param contentType
	 *            如:application/json;charset=utf8
	 * @param content
	 *            数据内容
	 * @DATE 2018年9月22日 下午10:30:48
	 */
	static String doHttpPostByRestTemplate(final String wsdlURL, final String contentType, final String content) {
		// http使用无参构造;https需要使用有参构造
		RestTemplate restTemplate = new RestTemplate();
		// 解决中文乱码
		List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
		converterList.remove(1);
		HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
		converterList.add(1, converter);
		restTemplate.setMessageConverters(converterList);
		// 设置Content-Type
		HttpHeaders headers = new HttpHeaders();
		headers.remove("Content-Type");
		headers.add("Content-Type", contentType);
		// 数据信息封装
		// 注意:和doHttpPostByHttpClient方法用的不是同一个HttpEntity
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(
				content, headers);
		String result = restTemplate.postForObject(wsdlURL, formEntity, String.class);
		return result;
	}
}

七、处理响应结果

总结 

到此这篇关于Idea调用WebService的关键步骤和注意事项的文章就介绍到这了,更多相关Idea调用WebService内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文