Post multipart request with Android SDK

前端 未结 12 1819
余生分开走
余生分开走 2020-11-22 04:38

I\'m trying to do something I thought would be relatively simple: Upload an image to a server with the Android SDK. I\'m found a lot of example code:

http://groups.g

12条回答
  •  终归单人心
    2020-11-22 05:19

    For posterity, I didn't see okhttp mentioned. Related post.

    Basically you build up the body using a MultipartBody.Builder, and then post this in a request.

    Example in kotlin:

        val body = MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                    "file", 
                    file.getName(),
                    RequestBody.create(MediaType.parse("image/png"), file)
                )
                .addFormDataPart("timestamp", Date().time.toString())
                .build()
    
        val request = Request.Builder()
                .url(url)
                .post(body)
                .build()
    
        httpClient.newCall(request).enqueue(object : okhttp3.Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                ...
            }
    
            override fun onResponse(call: Call?, response: Response?) {
                ...
            }
        })
    

提交回复
热议问题