Java 在 REST 服务中返回 XML 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1232897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return XML Response in REST Service
提问by Priyank
I am writing a RESTful web service where in I want to return a XML containing some resultset. I have used XSTREAM and parsed the object into XML string. Since I need to return this string, I need to know how to pass it back to the calling client.
我正在编写一个 RESTful Web 服务,其中我想返回一个包含一些结果集的 XML。我使用了 XSTREAM 并将对象解析为 XML 字符串。因为我需要返回这个字符串,所以我需要知道如何将它传递回调用客户端。
One way is to return the RESPONSE to the calling client. And my sample code here shows what it is that I am trying to do.
一种方法是将 RESPONSE 返回给调用客户端。我这里的示例代码显示了我正在尝试做什么。
@Path("somepath")
public class ClassToReturnXML
{
public Response methodToReturnXML()
{
ResponseBuilder builder = new ResponseBuilderImpl();
builder.type(MediaType.TEXT_XML);
builder.entity(myXMLString);
return builder.build();
}
}
Unfortunately it doesn't return the entity, though the status code is 200. Am I instantiating the ResponseBuilder incorrectly? I also saw somewhere that it should be instantiated as follows:
不幸的是,它没有返回实体,尽管状态代码是 200。我是否错误地实例化了 ResponseBuilder?我也在某处看到它应该被实例化如下:
ResponseBuilder builder = Response.status(200);
Please suggest what is the apt way to return XML in response.
请建议什么是返回 XML 作为响应的恰当方式。
I AM USING APACHE CXF for RESTFUL SERVICES. (Version 2.2.3 -- i guess) :DThanks in Advance for all the help.
我正在使用 APACHE CXF 提供 RESTFUL 服务。(版本 2.2.3 - 我猜) :D提前感谢所有帮助。
采纳答案by Priyank
It was just a cleaning problem. It eventually worked. I created the response in following way eventually.
这只是一个清洁问题。它最终奏效了。我最终以以下方式创建了响应。
Response response = Response.status(200).type(MediaType.TEXT_XML).entity(xmlString).build();
It works just fine. I hope it helps someone.
它工作得很好。我希望它可以帮助某人。
回答by Dave Anderson
Does the HTTP Response have the correct content-type header to identify that it is Xml i.e. text/xml
or application\xml
? Checkout The Proper Content Type for XML Feeds.
HTTP 响应是否具有正确的内容类型标头以标识它是 Xml ietext/xml
还是application\xml
?签出 XML 提要的正确内容类型。
The response status 200 is just one of the standard HTTP Response Codesthat means the request has succeeded so only return it if that is the case.
响应状态 200 只是标准HTTP 响应代码之一,这意味着请求已成功,因此只有在这种情况下才返回它。