客户端调用webservice2——URLConnection
代码:
package cn.zengfansheng.webservice.urlconnection;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class WebUrlConnection {
public static void main(String[] args) {
try {
//指定服务的请求地址
String wsUrl = "http://localhost:8080/sayhello";
URL url = new URL(wsUrl );
//打开网络连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置。。。
conn.setRequestProperty("content-type", "text/xml;charset=utf-8");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//构造请求体,符合SOAP规范
String requestBody = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://publish.webservice.zengfansheng.cn/\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
"<soapenv:Body><q0:sayHello><arg0>xiaosheng</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>";
// 向服务端写入数据
OutputStream out = conn.getOutputStream();
out.write(requestBody.getBytes());
int code = conn.getResponseCode();
if (code==200) {//响应成功
InputStream is = conn.getInputStream();
StringWriter sw = new StringWriter();
byte[] buf = new byte[1024];
int len = 0;
while ((len=is.read(buf))!=-1) {
String s = new String(buf, 0, len,"utf-8");
sw.append(s);
}
System.out.println(sw.toString());
// is.close();
}
//out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |