天气预报服务的调用

资源地址: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"



  
    
      string
    
  

测试类:

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("");
        soapRequestData.append("");
        soapRequestData.append("");
        soapRequestData.append("" + cityName + "");
        soapRequestData.append("");
        soapRequestData.append("");
        soapRequestData.append("");
        soapRequestData.append("");
        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文件



参考文章:

  • 通过xml形式请求webService
  • webservice通信调用天气预报接口实例

你可能感兴趣的:(天气预报服务的调用)