【发布时间】:2020-11-05 22:39:01
【问题描述】:
我正在使用改造库进行 API 调用,我想使用“form-data”方法将参数发送到我的服务器。我在 StackOverflow 上找到了this question,但目前还没有解决方案。请指导我,让我知道我是否可以提供更多详细信息。谢谢
【问题讨论】:
标签: android android-studio kotlin retrofit2 multipartform-data
我正在使用改造库进行 API 调用,我想使用“form-data”方法将参数发送到我的服务器。我在 StackOverflow 上找到了this question,但目前还没有解决方案。请指导我,让我知道我是否可以提供更多详细信息。谢谢
【问题讨论】:
标签: android android-studio kotlin retrofit2 multipartform-data
为什么不使用 Multipart? 这是一个使用电话号码、密码和 prfile pic 的简单用户信息的示例:
在您的活动中:
final RequestBody rPhoneNumber = RequestBody.create(MediaType.parse("text/plain"), "sample phone number");
final RequestBody rPassword = RequestBody.create(MediaType.parse("text/plain"), "sample phone password");
final MultipartBody.Part rProfilePicture = null;
Retrofit.Builder builder = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(baseUrl).client(Cookie.cookie.build());
Retrofit retrofit = builder.build();
final RequestHandler requestHandler = retrofit.create(RequestHandler.class);
rProfilePicture = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"),file)); //sample image file that you want to upload
Call<ServerMessage> call; //ServerMessage is a class with a String to store and convert json response
call = requestHandler.editProfile(rPhoneNumber, rPassword, rProfilePicture); //editProfile is in RequestHandler interface
call.enqueue(new Callback<ServerMessage>() {
@Override
public void onResponse (Call < ServerMessage > call2, Response < ServerMessage > response){
//your code here
}
@Override
public void onFailure (Call < ServerMessage > call, Throwable t) {
//your code here
}
});
在RequestHandler.java接口中:
@Multipart
@POST("/api/change-profile")
Call<ServerMessage> editProfile(@Part("phoneNumber") RequestBody rPhoneNumber,
@Part("oldPassword") RequestBody rPassword,
@Part MultipartBody.Part rProfilePicture);
在 ServerMessage.java 中:
public class ServerMessage {
private String message;
public String getMessage() {
return message;
}
}
【讨论】:
这个示例应该会有所帮助:
public interface AuthService {
@POST("register")
@Headers("Content-Type:application/x-www-form-urlencoded")
@FormUrlEncoded
Call<LoginResponse> loginSocial(@Field("provider") String provider, @Field("access_token") String accessToken }
【讨论】:
我知道这可能会迟到。我遇到了同样的挑战,这对我有用
val requestBody: RequestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("avatar", imageFile.toString())
.build()
@POST("avatar")
fun uploadProfilePicture(
@Header("Authorization") header: String?,
@Body avatar:RequestBody
): Call<UserResponse>
【讨论】: