Web 服务

81 阅读1分钟

假设要访问名为 "GetWeather" 的 Web 服务,该服务提供了一个名为 "GetCityWeather" 的操作,用于查询指定城市的天气信息。以下是连接到 Web 服务并发送请求的 Java 代码:

  1. 确定 Web 服务 URL

URL wsdlUrl = new URL("www.example.com/GetWeatherS…");

  1. 创建 SOAP 请求

// 创建请求消息 SOAPMessage requestMessage = MessageFactory.newInstance().createMessage(); SOAPEnvelope envelope = requestMessage.getSOAPPart().getEnvelope(); envelope.addNamespaceDeclaration("ns1", "www.example.com/Weather"); SOAPBody requestBody = envelope.getBody();

// 创建操作参数 QName cityName = new QName("www.example.com/Weather", "CityName"); SOAPElement cityElement = requestBody.addChildElement(cityName); cityElement.setValue("Shanghai");

3、发送请求

// 创建 SOAP 连接并发送请求消息 SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection connection = connectionFactory.createConnection(); SOAPMessage responseMessage = connection.call(requestMessage, wsdlUrl);

  1. 接收响应

// 读取响应消息 SOAPBody responseBody = responseMessage.getSOAPBody(); NodeList responseNodes = responseBody.getElementsByTagNameNS("*", "WeatherInfo");

  1. 处理响应

// 提取响应结果 if (responseNodes.getLength() > 0) { Node weatherInfoNode = responseNodes.item(0); String temperature = weatherInfoNode.getAttributes().getNamedItem("Temperature").getNodeValue(); String humidity = weatherInfoNode.getAttributes().getNamedItem("Humidity").getNodeValue(); System.out.println("Temperature: " + temperature + ", Humidity: " + humidity); } else { System.err.println("No weather information found."); }

这里的示例代码是使用 Java 中的标准 SOAP API 来连接到 Web 服务。SOAP API 是一组使用 XML 进行消息传递的协议和库,用于实现 Web 服务客户端和服务端之间的通信。请注意,使用不同的编程语言和库可能会有所不同,因此可以根据实际需求进行修改。