我有以下代码:
HttpGet httpGet = new HttpGet(serverAdress + "/rootservices");
httpGet.setHeader("Accept", "text/xml");
HttpResponse response = client.execute(httpGet, localContext);
String projectURL = XMLDocumentParser.parseDocument(response.getEntity().getContent(), "oslc_scm:scmServiceProviders", "rdf:resource");
String workItemURL = XMLDocumentParser.parseDocument(response.getEntity().getContent(), "oslc_cm:cmServiceProviders", "rdf:resource");
这里的问题是我读了两次HttpResponse对象。所以我第二次得到例外。但是虽然我知道这个问题,但我找不到一个简单的解决方案。那么什么是解决这个问题的好方法呢?
答案 0 :(得分:2)
将response.getEntity().getContent()
返回的输入流读入存储在局部变量中的byte[]
。请参阅Convert InputStream to byte array in Java。
byte[] content = IOUtils.toByteArray(response.getEntity().getContent());
String projectURL = XMLDocumentParser.parseDocument(new ByteArrayInputStream(content), "oslc_scm:scmServiceProviders", "rdf:resource");
String workItemURL = XMLDocumentParser.parseDocument(new ByteArrayInputStream(content), "oslc_cm:cmServiceProviders", "rdf:resource");
答案 1 :(得分:1)
仅读取一次响应内容,并将其复制到与XMLDocumentParser.parseDocument
兼容的某种缓冲区。然后直接从缓冲区解析数据,并根据需要多次。
答案 2 :(得分:-1)
你为什么不这样试试呢?
HttpGet httpGet = new HttpGet(serverAdress + "/rootservices");
httpGet.setHeader("Accept", "text/xml");
InputStream in = null;
HttpResponse response = client.execute(httpGet, localContext);
in = response.getEntity().getContent();
String projectURL = XMLDocumentParser.parseDocument(in, "oslc_scm:scmServiceProviders", "rdf:resource");
String workItemURL = XMLDocumentParser.parseDocument(in, "oslc_cm:cmServiceProviders", "rdf:resource");