第二种方式调用:通过java jdk 自带的一个类URLConnect(可以发送一个http 请求)
原理:我们可以通过URLConnect 这个对象,发送一个http 请求,往webservice 服务端 传送xml 格式的数据,
模拟soap 协议 ,因为soap协议就是在http 的基础上传送xml格式的数据..
package cn.itcast.client.webService;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;/** * 第二种方式 * 原理:我们可以通过URLConnect 这个对象,发送一个http 请求,往webservice 服务端 传送xml 格式的数据,模拟soap 协议 ,因为soap协议就是在http 的基础上传送xml格式的数据.. * @author Administrator * */public class URLConnectionInvoke { public static void main (String args[]) throws Exception{ URL url = new URL("http://192.168.9.100:7418/helloService"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //打开连接 connection.setDoInput(true);//如果要接服务端数据必须为true connection.setDoOutput(true);//如果要往服务端传数据必须为true connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); connection.setRequestMethod("POST");//接受客户端的请求方式是post //通过流往服务端写数据 OutputStream outputStream = connection.getOutputStream(); StringBuffer buffer = new StringBuffer(5000); buffer.append("拷贝xml格式的代码"); outputStream.write(buffer.toString().getBytes()); //拿返回的数据 InputStream ios = connection.getInputStream(); int length = 0; byte b[] = new byte[1024]; StringBuilder builder = new StringBuilder(); while((length = ios.read(b)) != -1){ String s = new String(b,0,length,"utf-8"); buffer.append(s); } }}