// 方法一:使用JAX-WS调用WebService接口
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
public class JAXWSTest {
public static void main(String[] args) {
try {
// 1. 创建WebService的URL地址
URL url = new URL("http://example.com/service?wsdl");
// 2. 创建QName对象,指定命名空间和Service名称
QName qname = new QName("http://example.com/", "ExampleService");
// 3. 创建Service对象
Service service = Service.create(url, qname);
// 4. 获取远程接口实例
ExamplePortType examplePort = service.getPort(ExamplePortType.class);
// 5. 调用方法
String result = examplePort.someMethod("param");
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 方法二:使用Apache CXF调用WebService接口
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class ApacheCXFTest {
public static void main(String[] args) {
try {
// 1. 创建JaxWsProxyFactoryBean对象
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
// 2. 设置Service的地址
factory.setAddress("http://example.com/service");
// 3. 设置Service接口类型
factory.setServiceClass(ExamplePortType.class);
// 4. 创建代理对象
ExamplePortType client = (ExamplePortType) factory.create();
// 5. 调用方法
String result = client.someMethod("param");
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 方法三:使用HTTPClient发送SOAP请求
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientSOAPTest {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 1. 创建HttpPost对象,指定请求地址
HttpPost httpPost = new HttpPost("http://example.com/service");
// 2. 设置SOAP消息体
String soapEnvelope = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:exa=\"http://example.com/\">" +
"<soapenv:Header/>" +
"<soapenv:Body>" +
"<exa:someMethod>" +
"<arg0>param</arg0>" +
"</exa:someMethod>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
// 3. 设置请求头
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", "someMethod");
// 4. 设置请求体
StringEntity entity = new StringEntity(soapEnvelope, "UTF-8");
httpPost.setEntity(entity);
// 5. 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String result = EntityUtils.toString(responseEntity);
System.out.println("Result: " + result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上一篇:java执行python脚本
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站