【问题标题】:How to POST Data using retrofit2 when i selected form-data in POSTMAN当我在 POSTMAN 中选择表单数据时如何使用改造 2 发布数据
【发布时间】:2018-12-17 05:53:34
【问题描述】:

当我过去使用改造通过 Api 发布数据时,当我在界面中使用 @FormUrlEncoded 但在邮递员中我使用表单数据发布时,我收到响应 400,你能帮帮我吗

这是我的界面

public interface SignupApiService {

@POST("users")
@FormUrlEncoded
Call<ResponseBody> savePost(@Field("email") String email,
                            @Field("password") String password,
                            @Field("role") int role);
}

这是我的注册活动

Call<ResponseBody> call = SignupClient
                        .getInstance().getApi()
                        .savePost(email, password, roleValue);

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        int statusCode = response.code();
                        progressBar.setVisibility(View.GONE);
                        Log.d("SignupActivity", "onResponse" +statusCode);

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(SignupActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

这是我的 Java 类

public class SignupClient {

private static SignupClient mInstance;
private static Retrofit retrofit;
private static final String BASE_URL = "http://74.207.233.160/api/v1/";

private SignupClient(){

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

public static synchronized SignupClient getInstance() {
    if (mInstance == null){
        mInstance = new SignupClient();
    }
    return mInstance;
}

public SignupApiService getApi() {
    return retrofit.create(SignupApiService.class);
}
}

在这里,当我使用 formurlencoded 时,我得到响应 400。 如何在此处使用formurlencoded 的表单数据。 或者我的邮递员需要进行任何更改

邮递员在这里成功时,我选择了表单数据

当我选择 form-url-encoded 时的邮递员

【问题讨论】:

  • 这和 JavaScript 有什么关系??
  • 你的反手可能有错误?
  • 只要去掉 FormDataUrl 注释,它仍然可以工作。 Postman 中的 form-data 用于将数据作为 Multipart 表单数据发送,我认为它不是 @FormUrlEncoded。你能发布你的后端 API 代码吗?
  • 你试过在邮递员中设置 content-type application/x-www-form-urlencoded 吗?

标签: java android retrofit retrofit2


【解决方案1】:

像这样编辑你的接口方法

@POST("users")
Call<ResponseBody> savePost(@PartMap() Map<String, RequestBody> map);

以及调用此方法的位置

Map<String, RequestBody> map = new HashMap<>();
map.put("user[email]", RequestBody.create(MultipartBody.FORM,email))
# same way add password and other params
and call the interface method by passing this map

【讨论】:

  • @PartMap 参数只能用于多部分编码。我得到这个错误
  • 如果我在界面中使用@Multipart,我会得到响应 500
  • 你可以添加更新的代码,它会更有帮助@Yas
猜你喜欢
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2021-04-02
  • 2016-01-18
  • 2020-06-02
  • 2019-11-04
  • 1970-01-01
相关资源
最近更新 更多