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;
    }
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值