如何使用Fuel for Kotlin过帐多部分/表单数据?

时间:2019-01-13 20:02:03

标签: android http kotlin multipartform-data

我需要向服务器发送POST请求。我应该传递一些参数和图像。我可以通过Postman做到这一点,但是我无法使用Fuel在我的Android应用(最新SDK)上做到这一点。

这是我正在使用的代码:

val formData = listOf("name" to "name")
val (_, _, result) = Fuel.upload("http://10.0.2.2:3000/test", parameters = formData)
                         .source { request, url -> imageFile } // type is File
                         .responseObject<CustomResponse>()

这是邮递员的屏幕截图: enter image description here

我无权访问后端代码,只有一些日志。似乎请求正文为空,文件也未上传。我怎样才能做到这一点?我很茫然。

我还尝试将参数作为jsonBody传递,这确实提交了正文,但是内容类型不是multipart / form-data,并且图像仍然丢失。

此JS代码有效

let formData = new FormData();
formData.append('name', 'name');
formData.append('image', this.file);
axios.post(`${API_URL}/test`, formData, {
    headers: {
        'Content-Type': 'multipart/form-data'
    }
}).then(console.log).catch(console.log)

编辑:我还尝试将文件作为DataPart传递,仍然没有。

3 个答案:

答案 0 :(得分:0)

经过一番尝试,终于找到了解决方案。 试试这个,我认为这会有所帮助。

    val params = listOf("email" to "test@email.com", "pass" to "123456")
    Fuel.upload("http://your-api-url.com/login", Method.POST, params)
        .responseString { _, _, result ->               
            when (result) {
                is Result.Failure -> {
                    print(result.getException().toString())
                }
                is Result.Success -> {
                    val data = result.get()
                    print(data)
                }
            }
        }

答案 1 :(得分:0)

我设法向服务器发送 POST 请求。我传递了一个参数和一个图像。

        //Prepare POST body
        val postBody = listOf("name" to "name")

        //Call the API.
        val (_, _, result) = Fuel.upload("http://10.0.2.2:3000/test", Method.POST , postBody)
            .add(BlobDataPart(myInputStream, name = "image", filename = "default.jpg", contentType = "image/jpeg"))
            .responseString()

        //If failed, then print exception. If successful, then print result.
        when (result) {
            is Result.Failure -> {
                println(result.getException())
            }
            is Result.Success -> {
                println(result.get())
            }
        }

您可以阅读相关文档here

答案 2 :(得分:-1)

经过一番挣扎,我发现了可行的方法:

val file = FileDataPart.from("path_to_your_file", name = "image")
val (_, _, result) = Fuel.upload("http://10.0.2.2:3000/test")
                 .add(file)
                 .responseObject<CustomResponse>()

在我的情况下,我不需要名称部分,但我会尝试添加InlineDataPart