我想在 Retrofit 中使用 JSON 数据调用 POST 方法(Magento REST API)(提供 JSON 作为 JsonObject)。为此,我按照 postman 的要求打电话,对我来说工作得很好。
我已经完成了如下的android部分,
API接口(interface)
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 方法调用 Retrofit API。
最佳答案
将您的代码更改为类似这样的内容,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;
}
}
关于android - 使用 Json 数据改造 POST 方法得到错误代码 400 : Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47904680/