package cn.itcast.service.urlconnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
* 通过UrlConnection调用Webservice服务
*
* @author *
*/
public class App {
public static void main(String[] args) throws Exception {
// 指定webservice服务的请求地址
String wsUrl = "http://192.168.1.108:5678/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");
// 手动构造请求体 请求体通过 httpwatch eclipse tcp/ip工具 还要myeclipse调用wsdl的 查看请求信息 可以获取
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> <arg1>10</arg1> </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,0,len,"UTF-8");
sb.append(str);
}
System.out.println(sb.toString());
is.close();
}
con.disconnect();
}
}