Android - HttpURLConnection не загружает несколько файлов - PullRequest
0 голосов
/ 20 сентября 2018

У меня есть IntentService для загрузки нескольких файлов на сервер:

@Override
protected void onHandleIntent(Intent intent) {
    //String urlToDownload = intent.getStringExtra("url");
    ArrayList<Uri> uris = (ArrayList<Uri>) intent.getSerializableExtra("uris");
    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
    String ur = intent.getStringExtra("urlheader");
    chiave = intent.getStringExtra("key");
    String urlUpload = ur + chiave;
    File sourceFile = null;
    FileInputStream fileInputStream = null;
    URL url = null;
    HttpURLConnection connection = null;
    DataOutputStream dos = null;
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    for (Uri u : uris) {
        try {

            url = new URL(urlUpload);
            connection = (HttpURLConnection) url.openConnection();
            //connection.connect();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            //connection.setRequestProperty("uploaded_file", fileName);
            dos = new DataOutputStream(connection.getOutputStream());


            Log.d("uploadFile", "uri: " + u);
            sourceFile = new File(getRealPathFromURI(u));
            fileInputStream = new FileInputStream(sourceFile);


            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file[]\"; filename=\""
                    + getName(getContentResolver(), u) + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = connection.getResponseCode();
            final String serverResponseMessage = connection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {
                Bundle resultData = new Bundle();
                resultData.putInt("progress", 1);
                receiver.send(UPDATE_PROGRESS, resultData);
            }


            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (IOException e) {
            Log.e(TAG, "Errore io: " + e);
        }
    }
}

Это работает, но, как вы можете видеть, оно создает новое соединение для каждого файла.Я хотел бы использовать одно соединение для всех файлов.

Для этого я просто поместил следующие строки:

        url = new URL(urlUpload);
        connection = (HttpURLConnection) url.openConnection();
        //connection.connect();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("ENCTYPE", "multipart/form-data");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        //connection.setRequestProperty("uploaded_file", fileName);
        dos = new DataOutputStream(connection.getOutputStream());

перед циклом for, но он загрузит только один файли ничего не делает после этого.Зачем?Что можно изменить, чтобы получить множественную загрузку только с одним подключением?

Обратите внимание, что при большем количестве файлов в журналах не печатается HTTP-ответ.Например, журналы с более чем двумя файлами:

D/uploadFile: uri: content://media/external/images/media/178689
I/uploadFile: HTTP Response is : OK: 200
D/uploadFile: uri: content://media/external/audio/media/25829
...