XML请求接口方式

将输入流转成键值对形式的属性对象

/**
 * 将输入流转成键值对形式的属性对象
 * @param is 输入流
 */
public static Properties stream2prop(InputStream is) throws IOException {
    
    
		ByteArrayOutputStream baos = null;
		ByteArrayInputStream bais = null;
		try {
    
    
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			while ((len = is.read(buffer)) > -1) {
    
    
				baos.write(buffer, 0, len);
			}
			baos.flush();
			byte[] data = baos.toByteArray();
			logger.info("报文数据:\r\n" + new String(data, "GBK"));
			bais = new ByteArrayInputStream(data);
			Properties prop = new Properties();
			// 将 XML 格式的参数转为 Properties 对象
			prop.loadFromXML(bais);
			return prop;
		} catch (Exception e) {
    
    
			logger.error("数据解析失败", e);
		} finally {
    
    
			if (baos != null) {
    
    
				baos.close();
			}
			if (bais != null) {
    
    
				bais.close();
			}
		}
	}

传参形式

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="userId"><![CDATA[1]]></entry>
    <entry key="userName"><![CDATA[Michelle]]></entry>
    <entry key="age"><![CDATA[18]]></entry>
</properties>

注意
传参时需加上

<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

否则会报错

java.util.InvalidPropertiesFormatException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 13; Document root element "properties", must match DOCTYPE root "null".

请求结果
在这里插入图片描述

Guess you like

Origin blog.csdn.net/Michelle_Zhong/article/details/105285177