欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Webservice调用天气接口案例

发布时间:2024/3/24 编程问答 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Webservice调用天气接口案例 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

废话不多说,希望能够帮助到大家。
天气接口:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
pom.xml配置:

com.sun.jersey
jersey-client
1.18
compile


com.alibaba
fastjson
1.2.24

import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.DefaultClientConfig; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element;import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;/*** @Description TOO* @Date 2022/8/3 0003 16:43*/ public class Test {public static void main(String[] args) throws DocumentException {post();}/***功能描述 :调用天气接口* @date 2022/8/3 0003* @param* @return java.lang.String*/public static String post() throws DocumentException {//创建客户端Client client = Client.create(new DefaultClientConfig());//指定资源WebResource webResource = client.resource("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl");//外网//path:请求的方法,entity请求的参数,type请求的格式,post请求方式(返回的类型)ClientResponse clientResponse = webResource.path("getSupportCity").entity("byProvinceName=湖南").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class);String xml = clientResponse.getEntity(String.class);System.out.println(xmlToJson(xml));System.out.println(xml);return xml;}/***功能描述 :将返回的xml转化为json* @author LKY* @date 2022/8/3 0003* @param*/public static JSON xmlToJson(String xml) throws DocumentException {List list = new ArrayList<>();//将xml格式的字符串转换成Document对象Document doc = DocumentHelper.parseText(xml);//获取根节点Element root = doc.getRootElement();//获取根节点下的所有元素List children = root.elements();//循环所有子元素if(children != null && children.size() > 0) {for(int i = 0; i < children.size(); i++) {Map map1 = new HashMap();Element child = (Element)children.get(i);map1.put(child.getName(), child.getTextTrim());list.add(map1);}}JSONArray jsonObject1 = (JSONArray) JSONObject.toJSON(list);return jsonObject1;} }

总结

以上是生活随笔为你收集整理的Webservice调用天气接口案例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。