Trying to upload a file to a JAX-RS (jersey) server

后端 未结 4 852
轻奢々
轻奢々 2020-12-08 03:24

I\'m trying to upload a file and other form data using multipart/form-data client with Jersey. I\'m uploading to a REST web service also using Jersey. Here is the server c

4条回答
  •  时光取名叫无心
    2020-12-08 04:15

    public DssResponse callPut(String url, Map headers, FileDataBodyPart[] filePath, String boundary, String[] jsonString) throws IOException {
        Client client = ClientBuilder.newClient().register(MultiPartFeature.class);
        WebTarget webTarget = client.target(url);
        Builder builder = webTarget.request(MediaType.MULTIPART_FORM_DATA);
        FormDataMultiPart multiPart = new FormDataMultiPart();
        for (int i = 0; i < filePath.length; i++) {
    
            if (!filePath[i].getFileEntity().exists()) {
                throw new IOException("Invalid Input File - " + filePath[i].getFileEntity().getAbsolutePath());
            }
    
            multiPart.bodyPart(new FileDataBodyPart(filePath[i].getName(), filePath[i].getFileEntity()));
        }
    
        if (boundary != null)
            multiPart.type(Boundary.addBoundary(new MediaType("multipart", "form-data", Collections.singletonMap(Boundary.BOUNDARY_PARAMETER, boundary))));
        for (String jstr : jsonString) {
            multiPart.field("Content-Type", jstr, MediaType.APPLICATION_JSON_TYPE);
        }
        if (headers != null) {
            for (Entry header : headers.entrySet()) {
                builder.header(header.getKey(), header.getValue());
                System.out.println(header.getKey() + "===============>>" + header.getValue());
            }
        }
    
        Response response = builder.accept(MediaType.APPLICATION_JSON).put(Entity.entity(multiPart, multiPart.getMediaType()));
    
        multiPart.close();
    
        // Assert.assertNotNull(response);
        if (response == null )
            throw new IOException ("Response is NULL");
    
        int status = response.getStatus();
    
        return dssResponse;
    }
    

提交回复
热议问题