美文网首页
天气预报服务的调用

天气预报服务的调用

作者: Cheysen | 来源:发表于2018-12-05 20:25 被阅读0次

资源地址:http://www.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl"
这里提供两种调用WebService服务的方法,过程中axis2的依赖包需自行添加。

通过axis2插件生成本地代理文件

axis2的安装使用自行搜索,这里提供一个转载的别人的链接。之后在Eclipse(idea也可)新建一个工程,将资源地址的wsdl文件下载copy到工程里面,利用axis2生成本地代理,如下图


接着写一个客户端类WeatherTest用来调用服务
public class WeatherTest {
    public static void main(String[] args) throws ServiceException, RemoteException {
        WeatherWSLocator locator = new WeatherWSLocator();
        WeatherWSSoapStub service = (WeatherWSSoapStub) locator.getPort(WeatherWSSoapStub.class);
        invokeGetSupportProvince(service);
        invokeGetSupportCityString(service);
        invokeGetWeather(service);
    }

    // 调用获取支持的省份、州接口
    private static void invokeGetSupportProvince(WeatherWSSoapStub service) throws RemoteException {
        // TODO Auto-generated method stub
        String[] provices = service.getRegionProvince();
        System.out.println("总共" + provices.length + "个区域省");
        int count = 0;
        for (String str : provices) {
            if (0 != count && count % 5 == 0) {
                System.out.println();
            }
            String regEx = "(.*?),(\\d+)";
            Pattern pattern = Pattern.compile(regEx);
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                System.out.print(matcher.group(1) + "\t");
                count++;
            }
        }
        System.out.println("\n"+"----------------------");
    }

    // 调用获取支持查询某个省份内的城市接口
    public static void invokeGetSupportCityString(WeatherWSSoapStub service) throws RemoteException {
        String provinceName;
        System.out.print("输入要查询的区域或省:");
        Scanner input = new Scanner(System.in);
        provinceName = input.next();
        String[] cities = service.getSupportCityString(provinceName);
        System.out.println("总共" + cities.length + "个市");
        for (int i = 0; i < cities.length; i++) {
            if (0 != i && i % 5 == 0) {
                System.out.println();
            }
            String regEx = "(.*?),(\\d+)";
            Pattern pattern = Pattern.compile(regEx);
            Matcher matcher = pattern.matcher(cities[i]);
            if (matcher.find()) {
                System.out.print(matcher.group(1) + "\t");
            }
        }
        System.out.println("\n"+"----------------------");

    }

    // 调用查询某个城市天气的接口
    public static void invokeGetWeather(WeatherWSSoapStub service) throws RemoteException {
        String cityName;
        System.out.print("输入要查询的城市:");
        Scanner input = new Scanner(System.in);
        cityName = input.next();
        String[] weatherInfo = service.getWeather(cityName, null);
        for (String str : weatherInfo) {
            System.out.println(str);
        }
    }
}

运行该类即可得到天气结果,需要注意的是这种方式返回的是字符串数组


以soap消息的方式发送http请求

soap的语法可去菜鸟教程或W3school查看。该方式返回的也是soap消息,因为soap基于XML,可将结果直接写入XML文件。soap请求体如下

POST /WebServices/WeatherWS.asmx HTTP/1.1
Host: ws.webxml.com.cn
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://WebXml.com.cn/getWeather"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getWeather xmlns="http://WebXml.com.cn/">
      <theCityCode>string</theCityCode>
    </getWeather>
  </soap:Body>
</soap:Envelope>

测试类:

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;

public class GetWeatherBySoap {
    public static void main(String[] args) throws HttpException, IOException {
        String inputCity;
        Scanner input = new Scanner(System.in);
        System.out.println("输入要查询天气的城市:");
        inputCity = input.next();
        soapRequest(inputCity);

    }

    // 将返回的soap消息写入xml
    public static void writeToXml(String str) {
        FileWriter writer;
        try {
            writer = new FileWriter("WeatherResult.xml");
            writer.write(str);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void soapRequest(String cityName) {
        String wsdl = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl";
        int time = 30000;
        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(wsdl);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(time * 3);
        client.getHttpConnectionManager().getParams().setSoTimeout(3 * time);
        StringBuffer soapRequestData = new StringBuffer("");
        soapRequestData.append("<soap:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
                + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
                + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        soapRequestData.append("<soap:Body>");
        soapRequestData.append("<getWeather " + "xmlns=\"http://WebXml.com.cn/\">");
        soapRequestData.append("<theCityCode>" + cityName + "</theCityCode>");
        soapRequestData.append("<theUserID></theUserID>");
        soapRequestData.append("</getWeather>");
        soapRequestData.append("</soap:Body>");
        soapRequestData.append("</soap:Envelope>");
        try {
            RequestEntity requestEntity = new StringRequestEntity(soapRequestData.toString(), "text/xml", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            System.out.println(soapRequestData.toString());
            int status = client.executeMethod(postMethod);
            System.out.println("status:" + status);
            InputStream response = postMethod.getResponseBodyAsStream();
            String resp = IOUtils.toString(response, "UTF-8");
            System.out.println(resp);
            writeToXml(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

生成的XML文件



参考文章:

相关文章

  • 天气预报服务的调用

    资源地址:http://www.webxml.com.cn/WebServices/WeatherWS.asmx?...

  • 分布式服务调用ServiceCaller(3)

    ServiceCaller 服务调用 服务调用逻辑 调用Request,包含调用的服务名称,参数 Hyrstrix...

  • 添加redis来提升天气预报系统的并发访问能力

    添加redis来提升天气预报系统的并发访问能力 1、为什么要使用redis: 及时响应 有效减少服务调用 开发环境...

  • Spring Cloud Hystrix断路器

    Hystrix介绍 当微服务之间调用的时候,假设A服务调用B服务,B服务调用C服务,如果调用链路上的任何一环出现异...

  • 服务雪崩、服务熔断、服务降级

    1. 服务雪崩 多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其他的微服务...

  • Hystrix

    什么是服务雪崩? 多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服...

  • Java进阶-Dubbo-进阶

    一、服务调用过程 1.1 服务调用方式   Dubbo 服务调用过程:   Dubbo 支持同步和异步两种调用方式...

  • Spring Cloud之Hystrix

    在微服务架构中,各个服务互相调用,底层的基础服务会被多个上层服务调用,这时如果底层服务出现故障,调用他的其他上层服...

  • 中国天气预报调用方法

    功能:记录下调用天气接口的方法中国天气https://cj.weather.com.cn/plugin/index...

  • 服务调用

    调用过程 找到 invoker 获取 负载均衡策略 根据负载均衡策略获取一个 invoker 经过过滤器 Dubb...

网友评论

      本文标题:天气预报服务的调用

      本文链接:https://www.haomeiwen.com/subject/lhxgcqtx.html