TtT23
TtT23

Reputation: 7030

How to read XML file and send it as a response in restlet

When a get request is invoked to my server, I'm trying to send an XML file as a response.

@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;

}

But nothing actually shows up as a response on the client side (Not 404, the header is correctly sent as Content-Type:text/xml; charset=UTF-8). What am I doing wrong?

Upvotes: 0

Views: 1096

Answers (1)

TtT23
TtT23

Reputation: 7030

I don't know why I was making this more complicated than necessary.

This is how I successfully sent XML file content as a response.

@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();
}

Upvotes: 1

Related Questions