Отслеживайте ход загрузки файла на устройство Android с помощью BufferedInputStream - PullRequest
0 голосов
/ 15 ноября 2018

Как отслеживать ход загрузки файла, когда Content-Type не является составным и "Content-Type", "application/octet-stream".Есть решение для подсчета в цикле, но они терпят неудачу, так как исходный поток перемещается по сети после записи в выходной поток.

Ниже приведен мой кусок кода

HttpURLConnection urlConnection = null;
URL url = new URL(strUrl);

if (Utils.isValidURLForHttp(strUrl)) {
    urlConnection = (HttpURLConnection) url.openConnection();
} else {
    urlConnection = (HttpsURLConnection) url.openConnection();
}

String headerString = "";
if (headers != null) {
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        // do stuff
        urlConnection.setRequestProperty(key, value);
        headerString += key + ": " + value + "\n";
    }
}
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
//urlConnection.setFixedLengthStreamingMode(1000);
urlConnection.setConnectTimeout(1000 * Constants.CONNECTION_TIME_OUT_SEC);
urlConnection.setReadTimeout(1000 * Constants.READ_TIME_OUT_IMAGE_UPLOAD_SEC);

String filePath = uri.getPath();
File file = new File(filePath);

OutputStream outputStream = urlConnection.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);

int bytesAvailable = fileInputStream.available();
int maxBufferSize = 32768;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);

byte[] buffer = new byte[(int) file.length()/* bufferSize*/];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
    Log.d("tagProgressUpload","Upload ");
}
outputStream.flush();
fileInputStream.close();


///
InputStream inputStream = null;
try {
    inputStream = new BufferedInputStream(urlConnection.getInputStream());

} catch (Exception ex) {
    inputStream = new BufferedInputStream(urlConnection.getErrorStream());
}


String jsonResponse = readResponseContents(inputStream);

String responseHeaders = getResponseHeaders(urlConnection);

Logger.getInstance().logInfo(strUrl +
        "\n" + Constants.APIVerbs.DELETE +
        "\n" + headerString +
        "Request body: " + body +
        "\n" + "Status Code: " + urlConnection.getResponseCode() +
        "\n" + "ResponseHeaders: " + responseHeaders +
        "\n" + "Response: " + jsonResponse
);

Response response = new Response();
response.setResponse(jsonResponse);
response.setStatusCode(urlConnection.getResponseCode());
response.setStatusMessage(urlConnection.getResponseMessage());

HashMap<String, String> headers = new HashMap<>();
for (Map.Entry<String, List<String>> entries : urlConnection.getHeaderFields().entrySet()) {
    headers.put(entries.getKey(), entries.getValue().get(0));
}
response.setResponseHeaders(headers);
return response;
...