Java解析SOAP API返回XML响应时出现Protocol error报错如何解决
问题根因
- 你调用的接口返回的是JSON包裹XML的混合结构,外层是
{"d":"[你的XML内容]"}格式的JSON,你直接把整段包含花括号的内容传给XML解析器,解析器无法识别XML根节点,触发格式错误。 - 你的代码逻辑存在缺陷:读取响应时还没读完所有内容,就把单行文本
inputLine直接传入XML解析器,单行内容不可能是合法的完整XML结构,也会导致解析失败。
修复方案
你需要先完整读取整个响应内容,提取出JSON中包裹的XML字符串后,再执行XML解析操作,示例实现如下:
1. 完整读取接口响应
String fullResp = ""; if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { sb.append(inputLine).append("\n"); } in.close(); fullResp = sb.toString(); }
2. 提取XML内容
推荐使用JSON解析库提取目标XML,兼容性更强:
// 需引入org.json依赖,也可替换为你项目中在用的其他JSON解析工具 import org.json.JSONObject; JSONObject respJson = new JSONObject(fullResp); String pureXml = respJson.getString("d");
如果暂时不想引入额外依赖,也可以临时用字符串截取的方式提取:
int xmlStart = fullResp.indexOf("<DATA>"); int xmlEnd = fullResp.lastIndexOf("</DATA>") + 7; String pureXml = fullResp.substring(xmlStart, xmlEnd);
3. 执行XML解析
将提取到的纯XML内容传入解析器即可正常解析:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); Document xmlDom = docBuilder.parse(new InputSource(new StringReader(pureXml))); // 后续原有解析逻辑正常使用 NodeList returnList = xmlDom.getElementsByTagName("DATA"); DOMParser parser = new DOMParser(); parser.parse(new InputSource(new StringReader(returnList.item(0).getTextContent()))); Document doc = parser.getDocument(); NodeList responsedata = doc.getDocumentElement().getChildNodes();
内容的提问来源于stack exchange,提问作者Patti Shaw
相关产品推荐
相关产品推荐

