使用Java根据别人写好的WSDL文件调用WebService服务

说明:笔记搬家

免费的WebService接口,可用于测试:

https://blog.csdn.net/Tomorrow_csdn/article/details/75043867

举例:

天气预报Web服务,数据来源于中国气象局
Endpoint :http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
Disco      :http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?disco
WSDL      :http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl

到浏览去访问这个地址http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl

WebService服务的三种途径Endpoint Disco WSDL

https://blog.csdn.net/xieyufei/article/details/11572839

使用PostMan Rest工具测试上面的WebService接口

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="http://WebXml.com.cn/">
	<soapenv:Header></soapenv:Header>
	<soapenv:Body>
		<tns:getSupportProvince>
			<param><param>
		</tns:getSupportProvince>
	</soapenv:Body>
</soapenv:Envelope>

 

这些构造信息,是怎么来的,都是通过wsdl文件里面的描述得来的,后面等我熟悉了在做详细描述(这里的大概意思就是,调用xmlns:tns="http://WebXml.com.cn/">这个限定名称(关于这个可以百度一下:WebServiceQName)下的getSupportProvince方法,如果有参数在方法名里面加<param>标签来指定(关于指定参数的问题,我在网上找的三个版本,No1: 使用<param>k:v</param>多个使用(k:v, k:v)No2使用<arg0>v0</arg0><arg1>v1</arg1>, No3使用参数名本身<cityName>v</cityName><cityCode>v</cityCode>),参数以键值对形式给出

 

Eclipse代码完成调用

配上一些代码【乱,烂】,仅仅笔记搬家,以后有个参考,不喜勿喷:

package cn.com.WebXml;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

public class TestMain {

	public static void main(String[] args) throws Exception {
		WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();
		// String requstParam = "ALL";
		String requstParam = "成都";
		// String[] allCity = serviceSoap.getSupportCity(requstParam);
		String[] weatherbyCityName = serviceSoap.getWeatherbyCityName(requstParam);
		// System.out.println(allCity);
		// for (String string : allCity) {
		// System.out.println(string);
		// }

		// System.out.println(weatherbyCityName.length);
		// System.out.println(weatherbyCityName[22]);
		// System.out.println(weatherbyCityName[weatherbyCityName.length - 1]);
		for (String string : weatherbyCityName) {
			System.out.println(string);
		}

	}

	/**
	 * 获取所有支持城市的描述,并打印在控制台(请看下面的优化版,并写入文件查看)
	 * 
	 */
	@Test
	public void testGetAllCityDesc() throws Exception {
		final WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();
		final String requstParam_byProvinceName = "ALL"; // 指定为ALL就获取所有的
		final String[] allCity = serviceSoap.getSupportCity(requstParam_byProvinceName);
		// Arrays.asList(allCity).forEach(cityNameAndCode -> {
		//
		// });
		final List<String> list = new ArrayList<String>(allCity.length);
		for (String cityNameAndCode : allCity) {
			System.out.println(cityNameAndCode);
			String cityCode = cityNameAndCode.replaceAll("[^0-9]", "");
			// String cityCode01 = cityNameAndCode.replaceAll("[^\\d]", "");
			// System.out.println(cityCode);
			// System.out.println(cityCode01);
			list.add(cityCode);
		}

		for (String cityCode : list) {
			String[] weatherbyCityName = serviceSoap.getWeatherbyCityName(cityCode);

			System.out.println(weatherbyCityName[weatherbyCityName.length - 1]);

			System.out.println("\n\n");
		}
	}

	/**
	 * 获取所有支持城市的描述,打印在控制台并写入文件-优化版
	 * 
	 * 说明:免费用户24小时内访问有规定数量(只有每天调直到获取全部数据,需要做点小处理,记录一个变量,好像每次获取所有的城市是随机的,所以每次获取顺序都不对,所以
	 * 城市也做一个文件,后面就读取文件获取了,见下一个版本)
	 * 
	 */
	@Test
	public void testGetAllCityDescGoodVersion() throws Exception {
		final WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();
		@SuppressWarnings("resource")
		final FileOutputStream outputStream = new FileOutputStream("cityDesc.txt", true); // 第二个参数是追加模式
		Arrays.asList(serviceSoap.getSupportCity("ALL")).forEach(cityNameAndCode -> {
			try {
				String[] cityInfo = serviceSoap.getWeatherbyCityName(cityNameAndCode.replaceAll("[^0-9]", ""));
				System.out.println(cityInfo[cityInfo.length - 1]);
				outputStream.write((cityInfo[cityInfo.length - 1] + "\n").getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * 问题1 版本
	 * 
	 */
	@Test
	public void testGetAllCityDescGoodVersion2() throws Exception {
		final WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();
		@SuppressWarnings("resource")
		final FileOutputStream outputStream1 = new FileOutputStream("city.txt");
		// String[] cityNameAndCode = serviceSoap.getSupportCity("ALL"); //
		// 已写入文件后,这里就不用调用了
		// for (String cityNameAndCode1Str : cityNameAndCode) {
		// outputStream1.write((cityNameAndCode1Str + "\n").getBytes());
		// }

		@SuppressWarnings("resource")
		final FileOutputStream outputStream2 = new FileOutputStream("cityDesc.txt", true); // 第二个参数是追加模式

		// 读取city文件获取城市
		final FileReader fileReader = new FileReader("city.txt");
		@SuppressWarnings("resource")
		BufferedReader br = new BufferedReader(fileReader);
		List<String> list = new ArrayList<>();
		new ArrayList<String>() {
			public static final long serialVersionUID = 1L;

			{
				String str = null;
				while (StringUtils.isNotEmpty((str = br.readLine()))) {
					System.out.println(str);
					add(str);
					// list.add(str);
				}
				list.addAll(this); // 我的理解是this就是new ArrayList<String>(),将整个List放入list但是这样做数据不对[list和new
									// ArrayList的数据不一致],原因不明,见下面版本
			}
		}.forEach(cityNameAndCodeX -> {
			try {
				String[] cityInfo = serviceSoap.getWeatherbyCityName(cityNameAndCodeX.replaceAll("[^0-9]", ""));
				if (StringUtils.isEmpty(cityInfo.toString().trim())) {
					return;
				}
				list.remove(cityNameAndCodeX);
				list.stream().forEach(x -> {
					try {
						outputStream1.write((x + "\n").getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
				System.out.println(cityInfo[cityInfo.length - 1]);
				outputStream2.write((cityInfo[cityInfo.length - 1] + "\n").getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * 问题2 版本
	 */
	@Test
	public void testGetAllCityDescGoodVersion3() throws Exception {
		final WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();
		@SuppressWarnings("resource")
		final FileOutputStream outputStream1 = new FileOutputStream("city.txt");
		// String[] cityNameAndCode = serviceSoap.getSupportCity("ALL"); //
		// 已写入文件后,这里就不用调用了
		// for (String cityNameAndCode1Str : cityNameAndCode) {
		// outputStream1.write((cityNameAndCode1Str + "\n").getBytes());
		// }

		@SuppressWarnings("resource")
		final FileOutputStream outputStream2 = new FileOutputStream("cityDesc.txt", true); // 第二个参数是追加模式

		// 读取city文件获取城市
		final FileReader fileReader = new FileReader("city.txt");
		@SuppressWarnings("resource")
		BufferedReader br = new BufferedReader(fileReader);
		List<String> list = new ArrayList<>();
		new ArrayList<String>() {
			public static final long serialVersionUID = 1L;

			{
				String str = null;
				while (StringUtils.isNotEmpty((str = br.readLine()))) {
					System.out.println(str);
					add(str);
					list.add(str);
				}
				// list.addAll(this); //改进为在上面一个一个添加,但是有个问题,就是读取文件的时候city.txt被清空了,list直接没有数据了
			}
		}.forEach(cityNameAndCodeX -> {
			try {
				String[] cityInfo = serviceSoap.getWeatherbyCityName(cityNameAndCodeX.replaceAll("[^0-9]", ""));
				if (StringUtils.isEmpty(cityInfo.toString().trim())) {
					return;
				}
				list.remove(cityNameAndCodeX);
				list.stream().forEach(x -> {
					try {
						outputStream1.write((x + "\n").getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
				System.out.println(cityInfo[cityInfo.length - 1]);
				outputStream2.write((cityInfo[cityInfo.length - 1] + "\n").getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * 不知道为啥不好使版本,以后坚决不写华而不实的代码了
	 * 
	 */
	@SuppressWarnings("resource")
	@Test
	public void testGetAllCityDescGoodVersion4() throws Exception {
		final WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();

		// 读取city文件获取城市
		BufferedReader br = new BufferedReader(new FileReader("city.txt"));
		List<String> list = new ArrayList<>();
		new ArrayList<String>() { // 凡是这种块的语句都是不能打断点调试的,所以没有绝对把握还是不要这么搞,不然就是自己给自己挖坑
			public static final long serialVersionUID = 1L;

			{
				String str = null;
				while (StringUtils.isNotEmpty((str = br.readLine()))) {
					System.out.println(str);
					add(str);
					list.add(str);
				}
				br.close(); // 流一定要关闭,不关闭会有警告
			}
		}.forEach(cityNameAndCodeX -> { // 从这个代码可以看出Lamdab华丽是华丽,不过水平没到那里去,不能保证里面的代码一定正确,出了错也没法调试,所以要好调试还是传统写法稳当些
			try {
				String[] cityInfo = serviceSoap.getWeatherbyCityName(cityNameAndCodeX.replaceAll("[^0-9]", ""));
				if (StringUtils.isEmpty(cityInfo[cityInfo.length - 1].trim())) {
					return;
				}
				final FileOutputStream outputStream1 = new FileOutputStream("city.txt"); // FileOutputStream在创建时,如果没有这个文件,则会自动创建一个
				// 如果有这个文件,则会先将这个文件清空
				list.remove(cityNameAndCodeX);
				list.stream().forEach(x -> {
					try {
						outputStream1.write((x + "\n").getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
				outputStream1.close();

				final FileOutputStream outputStream2 = new FileOutputStream("cityDesc.txt", true); // 第二个参数是追加模式
				System.out.println(cityInfo[cityInfo.length - 1]);
				outputStream2.write((cityInfo[cityInfo.length - 1] + "\n").getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * 传统版本【正确好使的】,有个问题,就是直接运行只运行一条数据或者几条就结束了,但是打断点就不是,没明白【是接口和网络的原因,代码是OK的】,反正每天运行一点点就能把所有支持的城市的简介获取下来
	 */
	@Test
	public void testGetAllCityDescGoodVersion5() {
		try {
			final WeatherWebServiceSoap serviceSoap = new WeatherWebServiceSoapProxy().getWeatherWebServiceSoap();
			String[] cityNameAndCode = serviceSoap.getSupportCity("ALL"); // 已写入文件后,这里就不用调用了[好像有很多重复的,所以要去重]
			Set<String> cityNameAndCodeSet = new LinkedHashSet<>(Arrays.asList(cityNameAndCode));
			FileOutputStream outputStream = new FileOutputStream("city.txt");
			for (String cityNameAndCode1Str : cityNameAndCodeSet) {
				outputStream.write((cityNameAndCode1Str + "\n").getBytes());
			}
			outputStream.close();

			// 读取city文件获取城市
			BufferedReader bufferedReader = new BufferedReader(new FileReader("city.txt"));
			List<String> list = new CopyOnWriteArrayList<String>();

			String str = null;
			while (StringUtils.isNotEmpty((str = bufferedReader.readLine()))) {
				System.out.println(str);
				list.add(str);
			}
			bufferedReader.close();

			for (String cityNameAndCodeX : list) {
				String[] cityInfo = serviceSoap.getWeatherbyCityName(cityNameAndCodeX.replaceAll("[^0-9]", ""));

				if (StringUtils.isEmpty(cityInfo[cityInfo.length - 1].trim())) {
					System.out.println("\n >>>>>>>>>>>>>>>>>>>>>>>>>>>今日的调用次数已满,请明天再来调用  \n");
					return;
				}

				final FileOutputStream outputStream1 = new FileOutputStream("city.txt");
				list.remove(cityNameAndCodeX);
				list.stream().forEach(x -> {
					try {
						outputStream1.write((x + "\n").getBytes());
					} catch (IOException e) {
						e.printStackTrace();
					}
				});
				outputStream1.close();

				final FileOutputStream outputStream2 = new FileOutputStream("cityDesc.txt", true); // 第二个参数是追加模式
				System.out.println(cityInfo[cityInfo.length - 1]);
				outputStream2.write((cityInfo[cityInfo.length - 1] + "\n").getBytes());
				outputStream2.close();
			}
		} catch (Exception e) {
			new RuntimeException("可能是远程的Web Service接口或者网络的原因,调用失败,请重试");
		}
	}

}

********************************* 不积跬步无以至千里,不积小流无以成江海 *********************************

猜你喜欢

转载自blog.csdn.net/weixin_42465125/article/details/88706935