使用HttpURLConnection发送Soap请求
说到webservice无非就是一个http请求。至于请求的方式,那就多种多样了。但无论如何,webserivce都是遵循一定的规范的这个规范就是WSDL,只要能看明白wsdl的描述,那么只要编写一个符合它规范的请求就能简单的调用webservice,以下是通过HttpURLConnection模拟Soap请求来调用一个webservice并获取返回的结果,至于怎么解析就看个人爱好了。
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class Sender {/** * 以下代码演示了如何使用HttpURLConnection发送Soap请求调用webservice,并获取结果 * @date 2011-12-9 * @param args * @throws MalformedURLException * @throws IOException */public static void main(String[] args) throws MalformedURLException, IOException {HttpURLConnection connection=(HttpURLConnection)new URL("http://localhost:8080/XFireService/services/BookService").openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestMethod("POST");connection.setRequestProperty("Content-Type","text/xml;charset=UTF-8");connection.setRequestProperty("soapaction","");connection.connect();//连接服务器OutputStream os=connection.getOutputStream();String xml="<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" >" +"<soapenv:Header/>" +"<soapenv:Body>" +"<putNames>" +"<in0>" +"<!--Zero or more repetitions:-->" +"<string>xxx</string>" +"<string>yyy</string>" +"</in0>" +"</putNames>" +"</soapenv:Body>" +"</soapenv:Envelope>";os.write(xml.getBytes());os.flush();os.close();InputStream is = connection.getInputStream();//获取数据,真正的请求从此处开始byte[] bts=new byte[is.available()];is.read(bts);System.out.println(new String(bts));}}
?
1 楼 shixiuteng 2012-08-24 你好,你有没有服务端的代码啊!