Android 不使用 MultiPart 通过 OKHTTP 上传文件

Android Upload a file via OKHTTP not using MultiPart

这是我必须上传文件的代码:

fun uploadFile(oid: String, file: Attachment, mime: String, callback: Callback): Call {
    val url = getURL(XelionOKHttpAPIRestLinks.UPLOAD_FILE.replace("__OID__", oid))
    var mediaType = mime.toMediaType()
    var body = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.originalLocation,
            RequestBody.create(mediaType, file.originalLocation)).build()
    val request = Request.Builder().url(url).headers(setHeaderUpload(mime, file.commonName, file.size.toString())).post(body).build()
    val call = client.newCall(request)
    call.enqueue(callback)
    return call
}

这对我来说很完美。但是服务器不支持 MultiPart。所以我需要一次性发送文件。这怎么可能?

我也试过 HTTPConnection:

     var async = object : AsyncTask<Void, Void, String>() {
        override fun doInBackground(vararg params: Void?): String {
            val url = URL(getURL(XelionOKHttpAPIRestLinks.UPLOAD_FILE.replace("__OID__", oid)))
            try {
                val urlConnection: HttpURLConnection = url.openConnection() as HttpURLConnection
                var nameOnly = attachment.commonName.split("/")
                urlConnection.setRequestMethod("POST")
                urlConnection.setDoOutput(true)
                urlConnection.setRequestProperty("Authorization", "xelion " + XelionPreferences.INSTANCE.authToken)
                urlConnection.setRequestProperty("Content-Type", mime)
                urlConnection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + nameOnly.last() + "\"")
                urlConnection.setRequestProperty("Content-Length", attachment.size.toString())
                urlConnection.connect()
                val fileOutput = FileOutputStream(file)
                var decodedBytes = Base64.decode(attachment.contentsB64String, Base64.NO_WRAP)
                fileOutput.write(decodedBytes)
                fileOutput.close()
                var responseCode = urlConnection.getResponseCode()
                callback.sendData("")
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return ""
        }
    }
    async.execute()
}

但是为此我遇到了这个问题:

java.net.ProtocolException: content-length promised 318848 bytes, but received 0

我missing/getting哪里错了?

我想大概是getBytes()

使用时要小心,因为必须传递字符编码参数,如.getBytes("UTF-8")

如果您不传递任何参数,它将使用系统默认值。

请点赞:

fileOutput.write("你的解码字符串".getBytes("UTF-8"));

经过多次尝试,在我的 AsyncTask 中使用它使其工作:

val url = URL(getURL(XelionOKHttpAPIRestLinks.UPLOAD_FILE.replace("__OID__", oid)))
            var baos = ByteArrayOutputStream()
            try {
                val urlConnection: HttpURLConnection = url.openConnection() as HttpURLConnection
                var nameOnly = attachment.commonName.split("/")
                urlConnection.setRequestMethod("POST")
                urlConnection.setDoInput(true)
                urlConnection.setDoOutput(true)
                urlConnection.setRequestProperty("Authorization", "xelion " + XelionPreferences.INSTANCE.authToken)
                urlConnection.setRequestProperty("Content-Type", mime)
                urlConnection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + nameOnly.last() + "\"")
                urlConnection.connect()
                var decodedBytes = Base64.decode(attachment.contentsB64String, Base64.DEFAULT)
                urlConnection.getOutputStream().write(decodedBytes)

                val `is`: InputStream = urlConnection.getInputStream()
                val b = ByteArray(1024)

                while (`is`.read(b) !== -1) baos.write(b)

                urlConnection.disconnect()
                callback.sendData("")
            } catch (e: MalformedURLException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return ""