1、接着学习调用WebService服务的第三种方法,通过UrlConnection调用Webservice服务。
2、还是一样,必须启动一个WebService服务,代码:
package com.wang.webservice.service;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService
public class HelloService {
public String sayHello( String name ){
System.out.println(name);
return "hello " + name;
}
public static void main(String[] args) {
Endpoint.publish("http://127.0.0.1:1234/helloservice", new HelloService());
}
}
与上一篇文章用的WebService服务端一样。启动,
3、编写客户端代码:
package com.wang.webservice.urlconnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/*
* 通过UrlConnection调用Webservice服务
*/
public class App {
public static void main(String[] args) {
URL wsUrl = null;
try {
wsUrl = new URL("http://127.0.0.1:1234/helloservice");
HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
OutputStream os = conn.getOutputStream();
//请求体
String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://service.webservice.wang.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ "<soapenv:Body><q0:sayHello><arg0>tom</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>";
os.write(soap.getBytes());
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
String s = "";
while( (len = is.read(b))!=-1 ){
String ss = new String(b,0,len,"UTF-8");
s += ss;
}
//返回的是拦截中的返回体;
System.out.println(s);
is.close();
os.close();
conn.disconnect();
} catch (MalformedURLException e) {
System.out.println("创建URL失败");
e.printStackTrace();
} catch (IOException e) {
System.out.println("URL打开失败");
e.printStackTrace();
}
}
}
这里面注解中的请求体和返回体,在上一篇文章中介绍了,这里不再重复,
运行后,调用WebService服务端成功。这种方法更底层一些;