Jersey 2 Multipart upload Client

前端 未结 2 1345
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 02:45

I want to write a simple jersey 2 client to upload a file. I\'m using Jersey 2.10.1 and wrote following server code:

@POST
@Consumes(MediaType.MULTIPART_FORM         


        
相关标签:
2条回答
  • 2020-12-30 03:11

    I've found my problem. I've missed to set the MediaType of the MultiPart and with the .request(MediaType.MULTIPART_FORM_DATA) I've set the expected MediaType of the response to MULTIPART_FORM_DATA. Here is the working code:

    public class Slimclient {
        private static final String TARGET_URL = "http://localhost:49158/rest/service/upload";
    
        public Slimclient() {
            Client client = ClientBuilder.newBuilder()
                .register(MultiPartFeature.class).build();
            WebTarget webTarget = client.target(TARGET_URL);
            MultiPart multiPart = new MultiPart();
            multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
    
            FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
                new File("C:/Users/Nicklas/Desktop/aab.txt"),
                MediaType.APPLICATION_OCTET_STREAM_TYPE);
            multiPart.bodyPart(fileDataBodyPart);
    
            Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(multiPart, multiPart.getMediaType()));
    
            System.out.println(response.getStatus() + " "
                + response.getStatusInfo() + " " + response);
        }
    
        public static void main(String[] args) {
            new Slimclient();
        }
    }
    
    0 讨论(0)
  • 2020-12-30 03:15

    Because your server side consumes MediaType.MULTIPART_FORM_DATA, your client code could use FormDataMultiPart directly instead of MultiPart.

    FormDataMultiPart multiPart = new FormDataMultiPart();
    
    0 讨论(0)
提交回复
热议问题