【问题标题】:How to read XML file and send it as a response in restlet如何读取 XML 文件并将其作为响应发送到 restlet
【发布时间】:2013-06-15 12:33:01
【问题描述】:

当对我的服务器调用 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,标头正确发送为 Content-Type:text/xml;charset=UTF-8)。我做错了什么?

【问题讨论】:

    标签: java android xml rest restlet


    【解决方案1】:

    我不知道为什么我让这变得比必要的复杂。

    这就是我成功发送 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多