Java调用Web service服务接口获取数据

对web Service获取数据 首先导入jar包

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.11.3</version>
		</dependency>

然后就是连接服务的通用类

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class WebServiceUtils {

	public static Document webServiceDownload(String callLocation,String callMethod) {
		InputStream is = null;
		HttpClient client = new HttpClient();
		Document document = null;
		PostMethod method = new PostMethod(callLocation+"/"+callMethod);
		// PostMethod method = new PostMethod("www.xxx.com/WeatherWSS/Weather.asmx/GetCityForecastByZIP");
		//需要传递参数时,设置消息头
		// method.setRequestHeader("Host", "www.xxx.com");
		// method.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		//需要传递的参数名ZIP,值为90001
		// method.setParameter("ZIP", "90001");
		try {
			client.executeMethod(method);
			is = method.getResponseBodyAsStream();
			 document = Jsoup.parse(is, "UTF-8", "");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return document;
	}
}

获得数据后的简单的解析

// 获取xml数据
			Document doc = WebServiceUtils.webServiceDownload(callLocation,callMethod);
			// 获取<table>标签的
			Elements elements = doc.getElementsByTag("Table");
			// 获取相应节点的内容
			Elements alertIds = doc.getElementsByTag("AlertId");

使用的jsoup提供类似JS获取html元素: getElementById(String id) 用id获得元素 getElementsByTag(String tag) 用标签获得元素 getElementsByClass(String className) 用class获得元素 getElementsByAttribute(String key) 用属性获得元素 同时还提供下面的方法提供获取兄弟节点:siblingElements(), firstElementSibling(), lastElementSibling();nextElementSibling(), previousElementSibling()

经验分享 程序员 微信小程序 职场和发展