使用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());    

}  

}

 }

}

 

转载于:https://www.cnblogs.com/xiaohanjy/p/11181408.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值