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

时间:2017-12-20 11:11:19

标签: android magento post retrofit2 bad-request

我想在Retrofit中使用JSON数据调用POST方法(Magento REST API)(将JSON提供为JsonObject)。为此,我打电话给邮递员,并为我工作。

POSTMAN

我已经完成了以下的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
);}

APIUtility类为

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类设为

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) {

        }
    });
}

使用带有正文的POST方法的CallRetrofit API。

3 个答案:

答案 0 :(得分:2)

将代码更改为此类代码,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);
}

这是用户类:

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;
    }
}

答案 1 :(得分:1)

我认为您为所有调用设置的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");

答案 2 :(得分:1)

试试这个

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'
    
  3. 5.User Model

    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;
        }
    
    
    }