使用 Json 数据改造 POST 方法得到错误代码 400:错误请求

Retrofit POST Method with Json data got error code 400 : Bad Request

我想在 Retrofit 中使用 JSON 数据调用 POST 方法(Magento REST API)(提供 JSON 作为 JsonObject)。为此,我按照邮递员的要求打电话给我,对我来说很好。

我已经完成了 android 部分,

API 界面

public interface APIService {

@POST("seq/restapi/checkpassword")
@Headers({
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json;charset=utf-8",
        "Cache-Control: max-age=640000"
})
Call<Post> savePost(
        @Body JSONObject jsonObject
);}

API效用class作为

public class ApiUtils {

private ApiUtils() {
}

public static final String BASE_URL = "http://xx.xxxx.xxx.xxx/api/rest/";
public static APIService getAPIService() {

    return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}

}

RetrofitClient class as

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

最后,调用函数如下

public void sendPost(JSONObject jsonObject) {

    Log.e("TEST", "******************************************  jsonObject" + jsonObject);
    mAPIService.savePost(jsonObject).enqueue(new Callback<Post>() {
        @Override
        public void onResponse(Call<Post> call, Response<Post> response) {
            if (response.isSuccessful()) {

            }
        }

        @Override
        public void onFailure(Call<Post> call, Throwable t) {

        }
    });
}

CallRetrofit API 与带有主体的 POST 方法。

将您的代码更改为类似这样的内容,GsonConverterFactory 将 User 对象转换为 json 本身。

public interface APIService {
    @POST("seq/restapi/checkpassword")
    @Headers({
        "Content-Type: application/json;charset=utf-8",
        "Accept: application/json;charset=utf-8",
        "Cache-Control: max-age=640000"
    })
    Call<Post> savePost(@Body User user);
}

这是用户 Class:

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

我认为您为所有调用设置的 GsonConverterFactory 会将您的 JSONObject 转换为 json。这就是为什么您的电话正文看起来可能与您想象的完全不同的原因。这是 gson.toJson(new JSONObject()) 的结果:

{ "nameValuePairs": {} }

尝试更改您发送到此的对象:

public class Credentials {
    private String username;
    private String password;

    ...
}

然后更新你的通话

public interface APIService {

@POST("seq/restapi/checkpassword")
@Headers({
    "Content-Type: application/json;charset=utf-8",
    "Accept: application/json;charset=utf-8",
    "Cache-Control: max-age=640000"
})
Call<Post> savePost(
    @Body Credentials credentials
);}

为确保您的调用正确,请调用

Gson gson = new Gson();
gson.toJson(new Credentials("test_username", "test_password");

试试这个

1.APIInterface.java

public interface APIInterface {

    /*Login*/
    @POST("users/login")
    Call<UserResponse> savePost(@HeaderMap Map<String, String> header, @Body UserModel loginRequest);

}

2.ApiClient.java

public class ApiClient {

    public static final String BASE_URL = "baseurl";
    private static Retrofit retrofit = null;


    public static Retrofit getClient() {
        if (retrofit == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
                    .connectTimeout(30, TimeUnit.MINUTES)
                    .readTimeout(30, TimeUnit.MINUTES)
                    .build();

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

}
  1. API 来电

    public void sendPost(JSONObject jsonObject) {
    
        LoginRequestModel loginRequest = new LoginRequestModel(userName, userPassword);
    
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
    
        APIInterface appInterface = ApiClient.getClient().create(APIInterface.class);
        System.out.println("Final" + new Gson().toJson(loginRequest));
    
        Call<LoginResponseModel> call = appInterface.savePost(header, loginRequest);
    
        call.enqueue(new Callback<LoginResponseModel>() {
            @Override
            public void onResponse(Call<LoginResponseModel> call, Response<UserModel> response) {
                hideProgressDialog();
    
                if (response.body()!=null) {
    
                } else {
                    Toast.makeText(mContext, "Invalid credentials", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<LoginResponseModel> call, Throwable t) {
                t.printStackTrace();
            }
        });
    

    }

  2. Gradle 文件中的依赖关系

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
    

5.User 型号

public class UserModel {

    @SerializedName("usename")
    @Expose
    String userEmail;

    @SerializedName("password")
    @Expose
    String userPassword;

    public UserModel(String userEmail, String userPassword) {
        this.userEmail = userEmail;
        this.userPassword = userPassword;
    }


}