设置HTTPS请求方式调用
时间: 2023-09-15 18:20:40 浏览: 48
使用HTTPS请求方式调用Web Service接口,需要使用HTTPS协议发送请求。下面是使用JaxWsDynamicClientFactory方式和HttpURLConnection方式分别调用HTTPS协议Web Service接口的示例代码:
1. 使用JaxWsDynamicClientFactory方式调用HTTPS协议Web Service接口:
```java
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("https://localhost:8443/HelloWorld?wsdl");
HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
httpConduit.getClient().setProxyServer("proxyHost");
httpConduit.getClient().setProxyServerPort(8080);
Object[] result = client.invoke("sayHello", "world");
System.out.println(result[0]);
```
上述代码中,首先创建了一个JaxWsDynamicClientFactory实例,然后使用该实例创建了一个Client对象,指定了HTTPS协议Web Service接口的WSDL文件地址。接着获取HTTPConduit对象,并设置代理服务器地址和端口。最后通过Client对象调用了Web Service接口中的sayHello方法,并传入了一个参数world。调用完成后,将返回值打印输出。
2. 使用HttpURLConnection方式调用HTTPS协议Web Service接口:
```java
String wsdlUrl = "https://localhost:8443/HelloWorld?wsdl";
URL url = new URL(wsdlUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setDoOutput(true);
String soapXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.jws/\">\n" +
"<soapenv:Header/>\n" +
"<soapenv:Body>\n" +
"<ser:sayHello>\n" +
"<arg0>world</arg0>\n" +
"</ser:sayHello>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>";
OutputStream os = conn.getOutputStream();
os.write(soapXml.getBytes());
os.flush();
os.close();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
br.close();
is.close();
}
conn.disconnect();
```
上述代码中,与调用HTTP协议Web Service接口的示例代码类似,只是在创建URL对象时指定了HTTPS协议,并强制转换为HttpsURLConnection对象。在发送HTTP请求时,会自动使用SSL协议进行加密数据传输。
需要注意的是,在使用HTTPS协议发送请求时,需要提供证书和信任证书的CA证书,才能建立起安全连接。如果是自签发的证书,则需要在客户端的信任证书库中添加该证书。如果是使用公开的证书,则不需要额外配置。