How to avoid OutOfMemoryError when uploading a large file using Jersey client

前端 未结 6 2144
难免孤独
难免孤独 2020-11-28 08:14

I am using Jersey client for http-based request. It works well if the file is small but run into error when I post a file with size of 700M:

Exception in thr         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 08:39

    Below is the code for uploading a (potentially large) file with chunked transfer encoding (i.e. streams) using Jersey 2.11.

    Maven:

    
        2.11
    
    
    
        
            org.glassfish.jersey.core
            jersey-client
            ${jersey.version}
        
        
        org.glassfish.jersey.media
            jersey-media-multipart
            ${jersey.version}
        
    
    

    Java:

    Client client = ClientBuilder.newClient(clientConfig);
    client.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");
    
    WebTarget target = client.target(SERVICE_URI); 
    InputStream fileInStream = new FileInputStream(inFile);
    String contentDisposition = "attachment; filename=\"" + inFile.getName() + "\"";
    System.out.println("sending: " + inFile.length() + " bytes...");
    Response response = target
                .request(MediaType.APPLICATION_OCTET_STREAM_TYPE)
                .header("Content-Disposition", contentDisposition)
                .header("Content-Length", (int) inFile.length())
                .put(Entity.entity(fileInStream, MediaType.APPLICATION_OCTET_STREAM_TYPE));
    System.out.println("Response status: " + response.getStatus());
    

提交回复
热议问题