使用HttpURLConnection访问webservices服务端
使用HttpURLConnection访问webservices服务端(拼装soap消息体访问方式,貌似用的比较少,当了解吧),代码如下:
package com.neusoft.sl.si;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ws_httpconnection_client {
public static void main(String[] args) throws Exception {
//定义要访问的webservices URL
URL url=new URL("http://127.0.0.1:8080/framework");
//打开连结 获取URLConnection对象
URLConnection urlLconnection=url.openConnection();
//强转为HttpURLConnection对象
HttpURLConnection httpurlcon=(HttpURLConnection)urlLconnection;
//打开输入输出
httpurlcon.setDoInput(true); httpurlcon.setDoOutput(true);
//设置请求方式
httpurlcon.setRequestMethod("POST");
//设置请求Content-Type为text/xml;charset=UTF-8
httpurlcon.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//组装消息体
StringBuffer data=new StringBuffer("");
data.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://neusoft.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> ");
data.append("<soapenv:Body>");
data.append("<q0:oService>");
data.append("<param>chang</param>");
data.append("</q0:oService>");
data.append("</soapenv:Body>");
data.append("</soapenv:Envelope>");
//根据HttpURLConnection获取输出流
OutputStream out=httpurlcon.getOutputStream();
//使用输出流吧消息体输出至服务端
out.write(data.toString().getBytes());
//请求回调函数,如果请求成功
if(httpurlcon.getResponseCode() == 200){
//获取输入流
InputStream in= httpurlcon.getInputStream();
//获取输入缓冲区
BufferedReader br=new BufferedReader(new InputStreamReader(in));
//读取响应消息
StringBuffer sp=new StringBuffer("");
String line=null;
while((line=br.readLine())!=null){
sp.append(line);
}
//解析响应消息,使用SAXReader对象
SAXReader sx=new SAXReader();
Document doc= sx.read( new StringReader(sp.toString()));
//使用xpath的方式获取标签为returnname这个元素的集合
List<Element> elelist=doc.selectNodes("//returnname");
//遍历元素集合
for(Element el : elelist){ System.out.println(el.getText());
}
}
}
}