模拟请求webservice并获取返回报⽂ 有时需要模拟请求webservice服务,并处理返回的报⽂,根据报⽂的信息进⾏业务处理。
样例代码如下:
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.HttpURLConnection;
import java.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Simulating request webservice
* 模拟请求WEBSERVICE样例
*
*/
public class SimRequestWS {
/**
* 模拟请求WEBSERVICE⽅法
* @param url 请求的Webservice地址
* @param request 请求的报⽂,XML格式的字符串
* @return
*/
public static Map<String,String> doRequestWS(URL url, String request) {
调用webservice服务HttpURLConnection connection = null;
String rspMsg = "";
String rspCode = "ERROR";
try {
byte[] requestBuf = (byte[]) null;
requestBuf = Bytes("gbk");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "text/plain");
DataOutputStream out = new DataOutputStream(
out.write(requestBuf);
out.flush();
out.close();
if (ResponseCode() != 200) {
System.out.println("ERROR: " + ResponseMessage());
}
InputStream in = InputStream();
ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
byte[] readBuf = new byte[100];
while (true) {
int ret = in.read(readBuf);
if (ret < 0)
break;
bufOut.write(readBuf, 0, ret);
}
byte[] rspBuf = ByteArray();
rspMsg = new String(rspBuf, "gbk");
rspCode = ResponseMessage();
} catch (Exception e) {
e.printStackTrace();
}
connection = null;
Map<String,String> map = new HashMap<String,String>();
map.put("rspCode", rspCode);
map.put("rspMsg", rspMsg);
return map;
}
public static void main(String[] args) throws Exception,
UnsupportedEncodingException {
URL url = new URL("172.168.27.154:8081/cxfdemo?wsdl");
Map<String,String> map =SimRequestWS.doRequestWS(
url,
"<soapenv:Envelope xmlns:soapenv=\"/soap/envelope/\" xmlns:ws=\"ws/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<catt:hello>"
+ "<arg0>李四</arg0>"
+ "</catt:hello>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>");
System.out.println(map);
}
}
模拟请求⼀个Webservice服务,返回信息如下:
{rspCode=OK, rspMsg=<soap:Envelope xmlns:soap="/soap/envelope/"><soap:Body><ns2:helloResponse xmlns:ns2="catt/
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论