【问题标题】:Get the XML string posted to JAXB web service endpoint获取发布到 JAXB Web 服务端点的 XML 字符串
【发布时间】:2019-09-03 10:15:53
【问题描述】:

我已配置如下 Web 服务端点。

@POST
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.TEXT_PLAIN})
@Path("/post")
public String postPerson(Person pers) throws Exception{
    String xml_string_posted="?";
    System.out.println(<xml_string_posted>);
    JAXBContext jc = JAXBContext.newInstance(Person.class);
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource());

    }

我的问题很简单。每当有 POST 请求提交到这个端点,如下所示,我怎样才能将下面发布的整个 XML 字符串放入一个变量中。

POST /JX-1.0/service/person/post HTTP/1.1
Host: 
Content-Type: application/xml
X-Requested-With: XMLHttpRequest

<?xml version="1.0"?>
<a>
<b>&name;</b>
</a>

【问题讨论】:

    标签: java json xml jaxb jax-ws


    【解决方案1】:

    由于 HttpServletRequest#getInputStream() 只能使用一次,如果您想获取原始正文请求,则必须更新方法的签名。

    例如,您可以在方法中添加一个字符串参数。有效负载将自动分配给此变量。

    @POST
    @Consumes({MediaType.APPLICATION_XML})
    @Produces({MediaType.TEXT_PLAIN})
    @Path("/post")
    public String postPerson(String bodyRequest) throws Exception{
        // your code...
    }
    

    作为替代方案,您可以使用 HttpServletRequest,如下所示:

    @POST
    @Consumes({MediaType.APPLICATION_XML})
    @Produces({MediaType.TEXT_PLAIN})
    @Path("/post")
    public String postPerson(@Context HttpServletRequest request) throws Exception{
        ServletInputStream inputStream = request.getInputStream();
        System.out.println(inputStream.isFinished());
        byte[] buffer = new byte[250];
        int read = inputStream.read(buffer);
        System.out.println(new String(buffer, 0, read));
        // ...
    }
    

    如果您需要原始签名,可以查看这个问题:How to read request.getInputStream() multiple times

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 2011-01-19
      • 1970-01-01
      • 2011-01-06
      • 2010-11-17
      相关资源
      最近更新 更多