Android @Multipart的改造删除默认标题

时间:2016-10-04 07:51:26

标签: java android rest multipartform-data retrofit2

发出@Multipart请求会为每个部分添加这些默认标头(Content-Transfer-Encoding,Content-Type),有没有办法删除它们?

//REQUEST BODY
--25d35373-d2c3-46a3-969f-f5a1fd5f781a 
Content-Disposition: form-data; name="client_id"
Content-Transfer-Encoding: binary <-- remove this one
Content-Type: application/json; charset=UTF-8 <-- remove this one
Content-Length: 34
"40ccfee680a844780a41fbe23ea89934"
//

注意:我无法访问服务器,因此我无法让服务器接受这些标头。

2 个答案:

答案 0 :(得分:2)

你可以通过这种方式自己构建多部分体(kotlin代码,但同样的想法可以用java表示):

private _headers = new Headers();
private _options = new RequestOptions({
  headers: this._headers,
  withCredentials: true
});
login(email, password): Observable < any > {
  return this._http
    .post(this._url + 'login', {
      email: email,
      password: password
    }, this._options)
    .map(
      (res: any) => {
        let user = JSON.parse(res._body).user;
        if (user) {
          this.isLogged = true;
          localStorage.setItem('User', JSON.stringify(user));
          return true;
        } else {
          return false;
        }
      }
    )
}

(*) - 这是val mpart = MultipartBody.Builder() .addFormDataPart("param", paramValue) .addPart(null, someRequestBody).build() // <-- (*) see explanation below //thus, service method should looks like this: @POST("upload/endpoint") fun upload(@Body parts: MultipartBody) 方法,当您将addPart(headers: Headers, reqBody: RequestBody)传递给标头时arg将删除除null之外的所有标头

答案 1 :(得分:0)

@POST(...)
suspend fun updateImage(@Body Body: RequestBody): Response<ResponseBody>

val uploadFile = File(...)
val bodyFile = uploadFile.asRequestBody("image/*".toMediaType())

val bodyBuilder = MultipartBody.Builder()
bodyBuilder.setType(MultipartBody.FORM)
bodyBuilder.addFormDataPart("img", uploadFile.name, bodyFile)

api.updateImage(bodyBuilder.build())

改造+协程