Android通过OKHTTP上载文件而不使用MultiPart

问题描述 投票:0回答:2

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

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

我在这里想念/弄错了什么?

android networking file-upload upload okhttp
2个回答
0
投票

我认为是关于getBytes()

使用时请小心,因为必须传递.getBytes("UTF-8")之类的字符编码参数>

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

请喜欢:

fileOutput.write(“ 您的已解码字符串

”。getBytes(“ UTF-8”));

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.