Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我不能使用HttpUrlConnection上传第一个文件块?_Java_Rest_Kotlin_Httpurlconnection - Fatal编程技术网

Java 为什么我不能使用HttpUrlConnection上传第一个文件块?

Java 为什么我不能使用HttpUrlConnection上传第一个文件块?,java,rest,kotlin,httpurlconnection,Java,Rest,Kotlin,Httpurlconnection,在我的项目中,我应该从一台服务器上逐块下载一个文件,并将每个文件立即上传到另一台服务器上 我有一个我应该从那里下载的文件的URL。让我们称之为downloadUrl 这就是我如何逐块下载文件的方式: val chunkSize = 1024 * 1024 BufferedInputStream(downloadUrl.openStream()).use { bis -> val buffer = ByteArray(chunkSize) var countBytesRea

在我的项目中,我应该从一台服务器上逐块下载一个文件,并将每个文件立即上传到另一台服务器上

我有一个我应该从那里下载的文件的URL。让我们称之为
downloadUrl

这就是我如何逐块下载文件的方式:

val chunkSize = 1024 * 1024

BufferedInputStream(downloadUrl.openStream()).use { bis ->
    val buffer = ByteArray(chunkSize)
    var countBytesRead: Int

    while (bis.read(buffer, 0, chunkSize).also { countBytesRead = it } != -1) {

        // I should send buffer to another server
    }
}
现在,我应该将每个块发送到另一台服务器。代码I:

val chunkSize = 1024 * 1024

BufferedInputStream(downloadUrl.openStream()).use { bis ->
    val buffer = ByteArray(chunkSize)
    var countBytesRead: Int

    val boundary = System.currentTimeMillis().toString(16)
    val chunks = fileContentLength / chunkSize + if (contentLength % chunkSize != 0L) 1 else 0

    while (bis.read(buffer, 0, chunkSize).also { countBytesRead = it } != -1) {
        uploadChunkOfFile(
            boundary = boundary,
            chunk = buffer,
            fileFullName = fileFullName,
            chunkId = chunkId,
            chunks = chunks.toInt()
        )
        chunkId++
    }
}

fun uploadChunkOfFile(boundary: String, chunk: ByteArray, fileFullName: String, chunkId: Int, chunks: Int): String {
    val url = "some_upload_url"
    val connection = url.openConnection() as HttpURLConnection
    val lineEnd = "\r\n"
    val twoHyphens = "--"

    val charset = "UTF-8"

    connection.readTimeout = 20000
    connection.connectTimeout = 20000

    connection.doInput = true
    connection.doOutput = true
    connection.useCaches = false
    connection.requestMethod = "POST"
    connection.setRequestProperty("Connection", "Keep-Alive")

    connection.addRequestProperty("token", "some_token")
    connection.addRequestProperty("Content-Type", "multipart/form-data; boundary=$boundary")

    val dos = DataOutputStream(connection.outputStream)

    dos.writeBytes("$boundary$lineEnd")

    // Send parameter #chunkId
    dos.writeBytes("Content-Disposition: form-data; name=\"chunk\"$lineEnd")
    dos.writeBytes("Content-Type: text/plain; charset=$charset$lineEnd")
    dos.writeBytes("Content-Length: " + chunkId.toString().length + lineEnd)
    dos.writeBytes(lineEnd)
    dos.writeBytes(chunkId.toString() + lineEnd)
    dos.writeBytes(twoHyphens + boundary + lineEnd)

    // Send parameter #chunks
    dos.writeBytes("Content-Disposition: form-data; name=\"chunks\"$lineEnd")
    dos.writeBytes("Content-Type: text/plain; charset=$charset$lineEnd")
    dos.writeBytes("Content-Length: " + chunks.toString().length + lineEnd)
    dos.writeBytes(lineEnd)
    dos.writeBytes(chunks.toString() + lineEnd)
    dos.writeBytes(twoHyphens + boundary + lineEnd)

    // Send parameter #name
    dos.writeBytes("Content-Disposition: form-data; name=\"name\"$lineEnd")
    dos.writeBytes("Content-Type: text/plain; charset=$charset$lineEnd")
    dos.writeBytes("Content-Length: " + fileFullName.length + lineEnd)
    dos.writeBytes(lineEnd)
    dos.writeBytes(fileFullName + lineEnd)
    dos.writeBytes(twoHyphens + boundary + lineEnd)

    // Send parameter #file
    dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"$fileFullName\"$lineEnd") // filename is the Name of the File to be uploaded

    dos.writeBytes("Content-Type: video/mp4$lineEnd")
    dos.writeBytes(lineEnd)

    dos.write(chunk)

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

    println(dos)

    dos.flush()
    dos.close()

    val responseCode = connection.responseCode
    val responseMessage = connection.responseMessage

    val br = if (responseCode in 200..299)
        BufferedReader(InputStreamReader(connection.inputStream))
    else BufferedReader(InputStreamReader(connection.errorStream))

    println("chunkId: $chunkId, chunks: $chunks") // I print each chunk id

    val sb = StringBuilder()
    var output: String?
    while (true) {
        output = br.readLine()
        if (output.isNullOrEmpty()) break;
        sb.append(output)
    }

    println(sb.toString()) // I print response body of request

    return sb.toString()
}
对于每个区块,我得到响应代码200,除了第一个区块

日志:

chunkId:0,chunks:17
响应代码:500
responseMessage:内部服务器错误
白标错误页此应用程序没有配置的错误视图,因此您将其视为一个回退。

周五12月27日12:54:43 UTC 2019发生意外错误(类型=内部服务器错误,状态=500)。500内部服务器错误 chunkId:1,chunks:17 响应代码:200 回答信息:好的 {“uploadedFiles”:[{“fileId”:“0deb7af7-28a8-11ea-be77-ae88efe3f04a”,“fileName”:“3c20c268-c19a-4b13-9135-1698f2f4da11.mp4”}] chunkId:2,chunks:17 响应代码:200 回答信息:好的 {“uploadedFiles”:[{“fileId”:“0e2319fe-28a8-11ea-ab01-aa6ef33510d7”,“fileName”:“3c20c268-c19a-4b13-9135-1698f2f4da11.mp4”}] chunkId:3,chunks:17 ...
chunkId: 0, chunks: 17
responseCode: 500
responseMessage: Internal Server Error
<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you are seeing this as a fallback.</p><div id='created'>Fri Dec 27 12:54:43 UTC 2019</div><div>There was an unexpected error (type=Internal Server Error, status=500).</div><div>500 Internal Server Error</div></body></html>
chunkId: 1, chunks: 17
responseCode: 200
responseMessage: OK
{"uploadedFiles":[{"fileId":"0deb7af7-28a8-11ea-be77-ae88efe3f04a","fileName":"3c20c268-c19a-4b13-9135-1698f2f4da11.mp4"}]}
chunkId: 2, chunks: 17
responseCode: 200
responseMessage: OK
{"uploadedFiles":[{"fileId":"0e2319fe-28a8-11ea-ab01-aa6ef33510d7","fileName":"3c20c268-c19a-4b13-9135-1698f2f4da11.mp4"}]}
chunkId: 3, chunks: 17
...