【问题标题】:Jersey MultiPartRequest receiving nullJersey MultiPartRequest 接收 null
【发布时间】:2020-06-15 12:36:34
【问题描述】:

我正在尝试使用 MultipartEntitybuilder 从客户端构建多部分请求:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addTextBody(MULTIPART_ID,
                    id,ContentType.TEXT_PLAIN);
            builder.addTextBody(DOCT, doc,ContentType.TEXT_PLAIN);
            final InputStreamBody fileBody = new InputStreamBody(cachedStream,
                    ContentType.create(MediaType.APPLICATION_OCTET_STREAM));
            builder.addPart(CONTENT_PART, fileBody);
            builder.addTextBody(OVERWRIT_PERMIT, String.valueOf(preventOverWrite),ContentType.TEXT_PLAIN);


            final HttpPut putMethod= new HttpPut(url);
        //    putMethod.setHeader("content-type", "multipart/form-data"
            putMethod.setEntity(builder.build());
            final CloseableHttpResponse response = httpClient.execute(storeMethod);

读到这里的资源类如下:

@Path("/somePath")
    @PUT
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response uploadFunction(@FormDataParam(value="id")  String id, @FormDataParam(value="doc") String doc,@FormDataParam(value="content") InputStream content,
                                        @FormDataParam(value="overwrite") Boolean flag) throws SomeException {

我正在使用带有 Jersey2 的弹簧靴。在这一步,当我尝试读取其中任何一个时,我得到所有这些参数的空值。因此响应会出​​现内部服务器错误。

我也加了:

register(MultiPartFeature.class);

对客户端和服务器应用程序。

另外还添加了依赖

<dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-multipart</artifactId>
            <scope>compile</scope>
        </dependency>

有人可以指出我缺少什么吗?我需要创建一个对象而不是使用@FormDataParam 来为服务器吗?我已经使用 multipart 正确搜索了很多,但我还不能修复它。

【问题讨论】:

    标签: java spring-boot jax-rs deserialization jersey-2.0


    【解决方案1】:

    我在使用解码器后解决了这个问题。还需要一个代表对象的DTO。所以上面的资源类更新为

    @Path("/somePath")
        @PUT
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
        public Response uploadFunction(FormDataMultiPart input){
        Map<String, List<FormDataBodyPart>> bodyParts = input.getFields();
        bodyParts.get("id").stream().findFirst().ifPresent(id-> dtoObject.setId(id.getValue()));
        }
    

    同样,对于其他字段,您也可以检索值。

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多