gpt4 book ai didi

java - 格式化 Web 服务响应

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:20:41 27 4
gpt4 key购买 nike

我使用以下函数来检索网络服务响应:

private String getSoapResponse (String url, String host, String encoding, String soapAction, String soapRequest) throws MalformedURLException, IOException, Exception {         
URL wsUrl = new URL(url);
URLConnection connection = wsUrl.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();

byte[] buffer = new byte[soapRequest.length()];
buffer = soapRequest.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();

httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Host", host);

if (encoding == null || encoding == "")
encoding = UTF8;

httpConn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("SOAPAction", soapAction);

httpConn.setDoOutput(true);
httpConn.setDoInput(true);

OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();

InputStreamReader is = new InputStreamReader(httpConn.getInputStream());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();

while(read != null) {
sb.append(read);
read = br.readLine();
}

String response = decodeHtmlEntityCharacters(sb.toString());

return response = decodeHtmlEntityCharacters(response);
}

但我对这段代码的问题是它返回了很多特殊字符并使 XML 的结构无效。
响应示例:

<PLANT>A565</PLANT>
<PLANT>A567</PLANT>
<PLANT>A585</PLANT>
<PLANT>A921</PLANT>
<PLANT>A938</PLANT>
</PLANT_GROUP>
</KPI_PLANT_GROUP_KEYWORD>
<MSU_CUSTOMERS/>
</DU>
<DU>

所以为了解决这个问题,我使用下面的方法并传递整个响应,用相应的标点符号替换所有特殊字符。

private final static Hashtable htmlEntitiesTable = new Hashtable();
static {
htmlEntitiesTable.put("&","&");
htmlEntitiesTable.put(""","\"");
htmlEntitiesTable.put("&lt;","<");
htmlEntitiesTable.put("&gt;",">");
}

private String decodeHtmlEntityCharacters(String inputString) throws Exception {
Enumeration en = htmlEntitiesTable.keys();

while(en.hasMoreElements()){
String key = (String)en.nextElement();
String val = (String)htmlEntitiesTable.get(key);

inputString = inputString.replaceAll(key, val);
}

return inputString;
}

但是另一个问题出现了。如果响应包含此段 &lt;VALUE&gt;&lt; 0.5 &lt;/VALUE&lt;如果这将通过该方法进行评估,则输出将是:

<VALUE>< 0.5</VALUE>

这使得 XML 的结构再次无效。数据是正确且有效的“< 0.5”,但将其包含在 VALUE 元素中会导致 XML 结构出现问题。

你能帮忙解决这个问题吗?也许我获得或建立响应的方式可以改进。有没有更好的方法来调用 Web 服务并从中获取响应?

如何处理包含“<”或“>”的元素?

最佳答案

你知道如何使用第三方开源库吗?

您应该尝试使用 apache commons-lang:

StringEscapeUtils.unescapeXml(xml)

以下堆栈溢出帖子中提供了更多详细信息:

how to unescape XML in java

文档:

http://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html http://commons.apache.org/proper/commons-lang/userguide.html#lang3 .

关于java - 格式化 Web 服务响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19405232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com