在多部分Web服务中使用JAXB

时间:2017-02-12 03:50:58

标签: java xml jaxb multipart

我使用multipart / mix编写Jersey客户端和服务器来发送请求。每个multipart bodypart都是一个Java类。使用JAXB来编组客户端的对象并在服务器端解组。

  1. 编组后,print out是xml文件,但是在发送到服务器后,为什么打印为com.path.data.io.BBody@2b8dd61d?我用whireshark检查,xml被发送过来。
  2. 答案:因为该多部分已将其解组为对象。

    1. 在服务器端出现此错误 javax.xml.bind.UnmarshalException
      • 链接异常: [org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1; prolog中不允许使用内容。]
    2. 回答,不需要在这里解组

      固定代码如下所示。

      Java Class

      @XmlRootElement(name="bBody")
      @XmlAccessorType(XmlAccessType.FIELD)
      public class BBody {
      
          @XmlAttribute
          String a;
          @XmlElement
          String b;
      
          public BBody() {}
      
          public void setA(String a) {
          this.a = a;
      }
      

      客户端代码

      public ClientResponse multikey(CommonRequest request)
          throws Exception {
      String server = request.getURL();
      URI path = URI.create(server).resolve("/" + multikey);
      
      Client client = Client.create();
      WebResource rRoot = client.resource(path);
      WebResource.Builder builder = rRoot.header("Date", date);
      
      // Construct a MultiPart with each operation as a body part
      MultiPart multiPart = new MultiPart();
      for (BBody bBody : request.getBBodyList()) {
          JAXBContext ctx = JAXBContext.newInstance(BBody.class);
          StringWriter writer = new StringWriter();
          ctx.createMarshaller().marshal(bBody, writer);
          String custString = writer.toString();
          _log.info ("custString is {}", custString);
            // here print  custString is <?xml version="1.0" encoding="UTF-8" standalone="yes"?><bBody a="2c741c38-f120"><b>foo</b></bBody>
      
          multiPart.bodyPart(new BodyPart(custString,  MediaType.APPLICATION_XML_TYPE));
      
      }
      ClientResponse result = builder.type(MultiPartMediaTypes.createMixed()).post(ClientResponse.class, multiPart)
      return  new result;
      

      }

      服务器端代码

       @POST
       @Path("{ignore: .+}")
       @Consumes("multipart/mixed")
       public Response bulk(MultiPart multiPart,
                       @Context HttpServletRequest request,
                       @Context HttpServletResponse response) throws SuspendExecution {
      
          for (BodyPart bodyPart : multiPart.getBodyParts()) {
              log.info("bodypart entity dump {}", bodyPart.getEntity());
              //no need extra unmashal
              BBody bBody = bodyPart.getEntityAs(BBody.class)           
          }
      }
      

0 个答案:

没有答案