java - 如何读取 XML 文件并将其作为 reSTLet 中的响应发送

标签 java android xml rest restlet

当向我的服务器调用 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/

相关文章:

java - 如何将 Power BI 嵌入到基于 Spring 的项目中?

java - 首次尝试使用链接参数失败的 Facebook 发布

java - import java.util.UUID 有什么用?

android - 如果在 Android 中达到特定日期和时间,我如何在后台检查

android - 如何使用android上的硬件后退按钮捕获事件?

xml - 如何从 xml.data 解析输入解析键值

xml - 使用augeas修改centos的firewalld区域文件丢失缩进

java - 在 Java 中设置 CompareTo() 方法

android - 如何在wordpress中显示Android的xml文件?

xml - 我想隐藏(不禁用) 'protect workbook' 命令栏 Excel(customUI)的评论选项卡