Working POST Multipart Request with Volley and without HttpEntity

前端 未结 5 1378
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 09:55

This is not really a question, however, I would like to share some of my working code here for your reference when you need.

As we know that HttpEntity

5条回答
  •  滥情空心
    2020-11-22 10:37

    Here is a Kotlin version of a class allowing multipart request with Volley 1.1.1.

    It's mostly based on @BNK's solution but slighly simplified. I did not notice any particular performance issue. I uploaded a 5Mb pic in about 3 seconds.

    class MultipartWebservice(context: Context) {
    
        private var queue: RequestQueue? = null
    
        private val boundary = "apiclient-" + System.currentTimeMillis()
        private val mimeType = "multipart/form-data;boundary=$boundary"
    
        init {
            queue = Volley.newRequestQueue(context)
        }
    
        fun sendMultipartRequest(
            method: Int,
            url: String,
            fileData: ByteArray,
            fileName: String,
            listener: Response.Listener,
            errorListener: Response.ErrorListener
        ) {
    
            // Create multi part byte array
            val bos = ByteArrayOutputStream()
            val dos = DataOutputStream(bos)
            buildMultipartContent(dos, fileData, fileName)
            val multipartBody = bos.toByteArray()
    
            // Request header, if needed
            val headers = HashMap()
            headers["API-TOKEN"] = "458e126682d577c97d225bbd73a75b5989f65e977b6d8d4b2267537019ad9d20"
    
            val request = MultipartRequest(
                method,
                url,
                errorListener,
                listener,
                headers,
                mimeType,
                multipartBody
            )
    
            queue?.add(request)
    
        }
    
        @Throws(IOException::class)
        private fun buildMultipartContent(dos: DataOutputStream, fileData: ByteArray, fileName: String) {
    
            val twoHyphens = "--"
            val lineEnd = "\r\n"
    
            dos.writeBytes(twoHyphens + boundary + lineEnd)
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"$fileName\"$lineEnd")
            dos.writeBytes(lineEnd)
            dos.write(fileData)
            dos.writeBytes(lineEnd)
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd)
        }
    
        class MultipartRequest(
            method: Int,
            url: String,
            errorListener: Response.ErrorListener?,
            private var listener: Response.Listener,
            private var headers: MutableMap,
            private var mimeType: String,
            private var multipartBody: ByteArray
        ) : Request(method, url, errorListener) {
    
            override fun getHeaders(): MutableMap {
                return if (headers.isEmpty()) super.getHeaders() else headers
            }
    
            override fun getBodyContentType(): String {
                return mimeType
            }
    
            override fun getBody(): ByteArray {
                return multipartBody
            }
    
            override fun parseNetworkResponse(response: NetworkResponse?): Response {
                return try {
                    Response.success(response, HttpHeaderParser.parseCacheHeaders(response))
                } catch (e: Exception) {
                    Response.error(ParseError(e))
                }
            }
    
            override fun deliverResponse(response: NetworkResponse?) {
                listener.onResponse(response)
            }
        }
    }
    

提交回复
热议问题