zl程序教程

您现在的位置是:首页 >  其他

当前栏目

模拟请求webservice并获取返回报文

模拟 获取 请求 返回 webservice 报文
2023-09-14 08:59:49 时间

     有时需要模拟请求webservice服务,并处理返回的报文,根据报文的信息进行业务处理。

     样例代码如下: 

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.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) {

 HttpURLConnection connection = null;

 String rspMsg = "";

 String rspCode = "ERROR";

 try {

 byte[] requestBuf = (byte[]) null;

 requestBuf = request.getBytes("gbk");

 connection = (HttpURLConnection) url.openConnection();

 connection.setDoOutput(true);

 connection.setDoInput(true);

 connection.setRequestMethod("POST");

 connection.setUseCaches(false);

 connection.setRequestProperty("Content-Type", "text/plain");

 connection.connect();

 DataOutputStream out = new DataOutputStream(

 connection.getOutputStream());

 out.write(requestBuf);

 out.flush();

 out.close();

 if (connection.getResponseCode() != 200) {

 System.out.println("ERROR: " + connection.getResponseMessage());

 InputStream in = connection.getInputStream();

 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 = bufOut.toByteArray();

 rspMsg = new String(rspBuf, "gbk");

 rspCode = connection.getResponseMessage();

 } 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("http://172.168.27.154:8081/cxfdemo?wsdl");

 Map String,String map =SimRequestWS.doRequestWS(

 url,

 " soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.com/\" "

 + " 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="http://schemas.xmlsoap.org/soap/envelope/" soap:Body ns2:helloResponse xmlns:ns2="http://catt.com/" return hello 李四 /return /ns2:helloResponse /soap:Body /soap:Envelope }



Uview封装请求方法 最近开发了一个UniApp程序,但是在遇到请求方法调用的时候,还是犹豫了,因为之前没有搞过这种,然后自己查了很多资料,发现市面的都不是很一样,经过自己的研究,自己根据官方文档总结了一些通过方法,供大家参考。
如何处理页面关闭时发送HTTP请求? 在实际项目开发中,可能会遇到这样的业务问题:如何在用户离开或关闭页面时发送HTTP请求给服务端?可能有人会觉得页面都关闭了,还需要发送什么请求,完全没必要噻。但如果真有这样的业务需求落到自己的头上,那么我们应该如何来实现呢?