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

前端 未结 6 2109
难免孤独
难免孤独 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:59

    In my case (Jersey 2.23.2) rschmidt13's solution gave this warning:

    WARNING: Attempt to send restricted header(s) while the [sun.net.http.allowRestrictedHeaders] system property not set. Header(s) will possibly be ignored.
    

    This can be solved adding the following line:

    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
    

    However I think a cleaner solution can be obtained using the StreamingOutput interface. I post a complete example hoping it could be useful.

    Client (File upload)

    WebTarget target = ClientBuilder.newBuilder().build()
                .property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024)
                .property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED")
                .target("");
    
    StreamingOutput out = new StreamingOutput() {
    
        @Override
        public void write(OutputStream output) throws IOException, 
                WebApplicationException {
    
            try (FileInputStream is = new FileInputStream(file)) {
    
                int available;
                while ((available = is.available()) > 0) {
                    // or use a buffer
                    output.write(is.read());
                }
            }
        }
    };
    
    Response response = target.request().post(Entity.text(out));
    

    Server

    @Path("resourcename")
    public class MyResource {
    
        @Context
        HttpServletRequest request;
    
        @POST
        @Path("thepath")
        public Response upload() throws IOException, ServletException {
    
            try (InputStream is = request.getInputStream()) {
                // ...
            }
        }
    }
    

提交回复
热议问题