请写出java通过拼接xml请求webservice服务的代码
时间: 2023-08-27 08:04:21 浏览: 112
下面是一个通过拼接XML请求Web服务的Java代码示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebServiceClient {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/MyWebService");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml");
String requestXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://example.com/webservice\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <web:MyOperation>\n" +
" <web:Param1>Value1</web:Param1>\n" +
" <web:Param2>Value2</web:Param2>\n" +
" </web:MyOperation>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
connection.setDoOutput(true);
connection.getOutputStream().write(requestXML.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们首先创建一个URL对象并打开一个HttpURLConnection。设置HTTP请求方法为POST并设置Content-Type为text/xml。 然后,我们创建一个包含所需参数的XML字符串,并将其发送到Web服务。 最后,我们读取响应并在控制台上打印它。
阅读全文