【问题标题】:Getting error code 400 bad request in retrofit but works on postman在改造中收到错误代码 400 错误请求,但适用于邮递员
【发布时间】:2021-05-04 16:55:07
【问题描述】:

我正在开发一个注册 API 它将json输入如下/请求参数

{"httpMethod":"POST",
"firstname":"Ali",
"lastname":"Patel",
"email":"alipatel05@gmail.com",
"password":"12345678",
"country":"Canada",
"state":"Quebec",
"city":"Montreal",
"type":"Parent"}

但是当我从 android 应用程序调用 api 时,它给了我不好的 响应 error code 400 但在邮递员上工作得很好。

我的 API 客户端

    public class APIClient {
    private static Retrofit retrofit = null;
    public static final String BASE_URL = "https://5r8ndtx9zc.execute-api.us-east-2.amazonaws.com/";

    public static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        /*Gson gson = new GsonBuilder()
                .setLenient()
                .create();*/

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

        return retrofit;
    }
}

我的 API 接口

public interface APIInterface {

    @Headers({
            "Content-Type: application/json;charset=utf-8",
            "Accept: application/json;charset=utf-8",
            "Cache-Control: no-cache"
    })
    @POST("vaccinesApi")
    Call<ResponseBody> registerUser(@Body JSONObject locationPost);

}

这是我的 api 调用

private void registerUser() {

        HashMap<String, String> newhashMap = new HashMap<>();
        JSONObject hashMap = new JSONObject();
        try {
            hashMap.put("httpMethod","POST");
            hashMap.put("firstname",mEditFirstName.getText().toString().trim());
            hashMap.put("lastname",mEditLastName.getText().toString().trim());
            hashMap.put("email",mEditEmail.getText().toString().trim());
            hashMap.put("password",mEditPassword.getText().toString().trim());
            hashMap.put("country","Canada");
            hashMap.put("state","Quebec");
            hashMap.put("city",mSelectedCity);
            hashMap.put("type",mUserType);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Call<ResponseBody> call = apiInterface.registerUser(hashMap);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                progressDialog.hide();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    Log.e("SignupFragment", jsonObject.toString());
                    if (response.code() == 200) {
                        Toast.makeText(RegistrationActivity.this, "Success",Toast.LENGTH_SHORT).show();
                    /*Intent intent = new Intent(RegistrationActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finishAffinity();*/
                    } else {
                        Toast.makeText(RegistrationActivity.this, "Failed",Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                progressDialog.hide();
                call.cancel();
                Toast.makeText(RegistrationActivity.this, "Failed",Toast.LENGTH_SHORT).show();
            }
        });
    }

我是否需要更改我的界面,否则我的 api 调用中可能会出现一些错误?

感谢安万斯

【问题讨论】:

  • 我在浏览器中打开你的网址,得到这个{"message":"Internal Server Error"},这是500 错误代码不是400,在你的浏览器中试试这个5r8ndtx9zc.execute-api.us-east-2.amazonaws.com/vaccinesApi
  • @miladsalimi 这是因为您直接调用没有正文的 api {"httpMethod":"POST", "firstname":"Ali", "lastname":"Patel", "email":" alipatel05@gmail.com", "password":"12345678", "country":"Canada", "state":"Quebec", "city":"Montreal", "type":"Parent"} 这是 api body 在邮递员中调用它会起作用,但在 android 应用程序中不起作用
  • @PrajwalWaingankar 不,我正在使用原始数据请求,请检查我的问题。
  • @AliPatel 检查答案,看看它是否能解决您的问题

标签: android api retrofit retrofit2 okhttp


【解决方案1】:

问题在于您的locationPost 类型,它应该是JsonObject不是 JSONObject,因此请尝试以下方法之一

方法 1

API 接口

Call<ResponseBody> registerUser(@Body JsonObject locationPost);

API 调用

JsonObject obj = new JsonObject();
obj.addProperty("httpMethod","POST");
obj.addProperty("firstname",firstNameValue);

// add the rest of the field

Call<ResponseBody> call = apiInterface.registerUser(obj);

//rest of the logic remains same

方法 2

创建代表对象的POJO类并传递对象的实例

public class RequestObject{

final String  httpMethod, firstname;
// declare member variables for all the keys

   RequestObject(String method,String firstname){
        this.httpMethod = method;
        this.firstname = firstname;
   }
}

API 接口

Call<ResponseBody> registerUser(@Body RequestObject locationPost);

API 调用

RequestObject requestobject = new RequestObject("POST","firstName");
// add the rest of the field

Call<ResponseBody> call = apiInterface.registerUser(requestObject);

//rest of the logic remains same

【讨论】:

  • 感谢您的回复,您的方法 1 帮助了我。
  • 很高兴您的问题得到解决,编码愉快:)
【解决方案2】:

我认为你必须重新仔细检查这些参数。

{
    "httpMethod": "POST",
    "firstname": "Ali",
    "lastname": "Patel",
    "email": "alipatel05@gmail.com",
    "password": "12345678",
    "country": "Canada",
    "state": "Quebec",
    "city": "Montreal",
    "type": "Parent"
}

【讨论】:

  • 不,我使用的是 JSONObject 而不是 JsonObject。那是唯一的问题。无论如何感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 2018-07-07
  • 2020-05-02
  • 2018-07-22
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 1970-01-01
相关资源
最近更新 更多