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

问题描述 投票:2回答:3

我想在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) {

        }
    });
}

CallRetrofit API与POST方法一起使用。

android magento post retrofit2 bad-request
3个回答
3
投票

将代码更改为此类代码,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
投票

我认为你为所有调用设置的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
投票

试试这个

1.API interface.Java

public interface APIInterface {

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

}

2.API client.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.用户模型

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


}
© www.soinside.com 2019 - 2024. All rights reserved.