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()

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值