webservice(三)

来源:互联网 发布:python r语言 编辑:程序博客网 时间:2024/06/05 00:28

主题:利用httpUrlConnection进行webservice访问

想要利用httpUrlConnection访问webservice,必须利用携带消息体,并且必须知道响应体的格式才知道获取的节点

利用工具包


下面是通过eclipse访问得到的消息体


下面是代码:

package Client2;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.URI;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 Client {public static void main(String[] args) throws Exception{URL url =  new URL("http://127.0.0.1:8080/datetime");URLConnection connection = url.openConnection();HttpURLConnection httpURLConnection = (HttpURLConnection)connection;httpURLConnection.setDoInput(true);httpURLConnection.setDoOutput(true);httpURLConnection.setRequestProperty("Content-Type","text/xml;charset=UTF-8");httpURLConnection.setRequestMethod("POST");String data = ""+""+"";//获得输出流OutputStream out = httpURLConnection.getOutputStream();//发送数据out.write(data.getBytes());//判断请求成功if(httpURLConnection.getResponseCode() == 200){//获得输入流InputStream in = httpURLConnection.getInputStream();//使用输入流的缓冲区BufferedReader reader = new BufferedReader(new InputStreamReader(in));StringBuffer sb = new StringBuffer();String line = null;//读取输入流while((line = reader.readLine()) != null){sb.append(line);}//创建sax的读取器SAXReader saxReader = new SAXReader();//创建文档对象Document doc = saxReader.read(new StringReader(sb.toString()));//获得请求响应return元素List eles = doc.selectNodes("//return");for (Element ele : eles){System.out.println(ele.getText());}}}}
运行结果:2017-04-11

本例子的webservice在上一篇文章有。

最后,本来想写一篇ajax访问webservice的,其实访问形式都差不多,就是携带消息体,然后解析响应体


0 0
原创粉丝点击