当向我的服务器调用 get 请求时,我尝试发送 XML 文件作为响应。
@Get
public Representation getRootDeviceXML() throws IOException {
File xmlFile = new File("rootdevices.xml");
if (!xmlFile.exists())
throw new ResourceException(Status.SERVER_ERROR_INTERNAL);
SaxRepresentation result;
try {
InputStream inputStream = new FileInputStream(xmlFile);
InputSource inputSource = new InputSource(new InputStreamReader(
inputStream));
result = new SaxRepresentation(MediaType.TEXT_XML, inputSource);
} catch (IOException e) {
throw new IOException(e.toString());
}
Writer writer = new OutputStreamWriter(System.out);
result.write(writer);
return result;
}
但实际上客户端上没有显示任何响应(不是 404, header 正确发送为 Content-Type:text/xml; charset=UTF-8)。我做错了什么?
最佳答案
我不知道为什么我要让事情变得比必要的更复杂。
这就是我成功发送 XML 文件内容作为响应的方法。
@Get ("xml")
public String getRootDeviceXML() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(xmlFile));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
br.close();
return sb.toString();
}
关于java - 如何读取 XML 文件并将其作为 reSTLet 中的响应发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17123679/