第四种方式
通过urlConnection连接webservicce
1.服务必须启动
2..
ackage cn.itcast.service.uriconnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class App2 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String wsUrl = "http://localhost:5084/hello";
URL url = new URL(wsUrl);
URLConnection conn = url.openConnection();
HttpURLConnection con = (HttpURLConnection) conn;
// 设置请求方式
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("content-type","text/xml;charset=UTF-8");
// 手动构造请求体
String requestBody = "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" "+
" xmlns:q0="http://service.itcast.cn/" ? ?xmlns:xsd="http://www.w3.org/2001/XMLSchema" "+ ?
" ?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> " +
"<soapenv:Body><q0:sayHello><arg0>lisi</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>";
;
//获得输出流
OutputStream out = con.getOutputStream();
out.write(requestBody.getBytes());
out.close();
int code = con.getResponseCode();
if(code == 200){//服务端返回正常
InputStream is = con.getInputStream();
byte[] b = new byte[1024];
StringBuffer sb = new StringBuffer();
int len = 0;
while((len = is.read(b)) != -1){
String str = new String(b,len,"UTF-8");
sb.append(str);
}
System.out.println(sb.toString());
is.close();
}
con.disconnect();
}
}
3.但必须解析xml