1

I am using okhttp3 to send a video from a Android phone to a Java servlet. When I send multiple files the first couple files are sent but at some point I start getting this exception:

java.net.ProtocolException: expected 2030 bytes but received 2362
at okhttp3.internal.http.Http1xStream$FixedLengthSink.write(Http1xStream.java:283)

My android code to send the video file is:

import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DataTransfer {
    public static void sendFile(final String method, final String path, final String fileSubType, final HashMap<String, String> hm ) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();

                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                builder.addFormDataPart("file", path, RequestBody.create(MediaType.parse(fileSubType), new File(path)));

                Set<String> set = hm.keySet();
                for (String s : set) {
                    builder.addFormDataPart(s,hm.get(s));
                }

                RequestBody request_body = builder.build();

                try {
                    Log.e(Constants.TAG, "++++++++++++++++++++++\n\n\nSIZE = " + request_body.contentLength() + "\n\n\n====================================\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Request request = new Request.Builder()
                        .url(Constants.URL + "/" + method)
                        .post(request_body)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    Log.d(Constants.TAG, "+++++++++++++++++++++\n" + response.body().toString() + "===========================================");
                    if(!response.isSuccessful()){
                        throw new IOException("Error : "+response);
                    }
                } catch (IOException e) {
                    Log.d(Constants.TAG, Log.getStackTraceString(e));
                }
            }
        });

        t.start();
    }
}

Java servlet code to receive file:

@RequestMapping(value="/dataTransfer", method = RequestMethod.POST)
    protected void dataTransfer(HttpServletRequest request, HttpServletResponse response) throws Exception {        
        try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            List<File> files = new ArrayList<File>();//Holds all the files that were received
            HashMap<String, String> map = new HashMap<String, String>();
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    map.put(fieldName, fieldValue);
                } else {
                    // Process form file field (input type="file").
                    String fileName = FilenameUtils.getName(item.getName());//If the name was not specified set default

                    String filePath = Constants.ORIGINAL_DIRECTORY_PATH + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);

                    files.add(storeFile);
                }
            }

            //Do other stuff to file
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        }
    }

And on the server side I get this error message:

org.apache.commons.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly

Why is this happening? How can I fix it?

----------------------------- Edit 8/10/17---------------

Figured out that it wasn't a server but a android problem because if I comment everything out of the servlet the same problem happens.

develop1
  • 747
  • 1
  • 10
  • 32

1 Answers1

0

Ususally this kind of error happens because your thread quit before the buffer flush.

You eliminate this by puttying a finally block that close stream/files gracefully, seems like you're missing one in the server.

See this answer..

ApriOri
  • 2,618
  • 29
  • 48
  • I don't have any open streams/files, the only place in the server where I do file I/O is `item.write(storeFile);` but I can't close this. – develop1 Aug 09 '17 at 16:18