我正在尝试使用Retrofit2向我们的AWS lambda服务器(https://
)发送请求,但服务器无法读取我传递的参数。但是,当我尝试使用指向我们本地网络(http://
)的相同代码时,它可以工作。以下是我的代码,请帮助。
Gradle Dependencies:
compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"
compile 'com.squareup.okhttp3:logging-interceptor:3.10.0'
请求类:
public class LoginRequest {
@SerializedName("login_credential")
private String credential;
@SerializedName("password")
private String password;
public LoginRequest(String credential, String password) {
this.credential = credential;
this.password = password;
}
}
改造初始化:
public class ServerClient {
public static Login getClient() {
HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
logger.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logger)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://my.server.ap-southeast-1.amazonaws.com/dev/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(Login.class);
}
public interface Login {
@Headers("Accept: application/json")
@POST("login")
Call<LoginResponse> login(@Body LoginRequest request);
}
}
我触发请求的方式:
Call<LoginResponse> call = ServerClient.getClient().login(new LoginRequest(email, password));
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(@NonNull Call<LoginResponse> call, @NonNull Response<LoginResponse> response) {
if (response.body() != null) {
Log.e("response", "success");
}
}
@Override
public void onFailure(@NonNull Call<LoginResponse> call, @NonNull Throwable t) {
Log.e("response", "failed");
}
});
这是日志:
D/OkHttp: --> POST https://my.server.ap-southeast-1.amazonaws.com/dev/login
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: Content-Length: 69
D/OkHttp: Accept: application/json
D/OkHttp: {"login_credential":"valid@email.com","password":"password"}
D/OkHttp: --> END POST (69-byte body)
D/OkHttp: <-- 400 https://my.server.ap-southeast-1.amazonaws.com/dev/login (966ms)
D/OkHttp: content-type: application/json
D/OkHttp: content-length: 138
D/OkHttp: date: Wed, 07 Mar 2018 05:16:54 GMT
D/OkHttp: x-amzn-requestid: c05224a1-21c6-11e8-b75f-3bdafa88fe40
D/OkHttp: access-control-allow-origin: *
D/OkHttp: x-amzn-remapped-content-length: 138
D/OkHttp: x-amzn-trace-id: sampled=0;root=1-5a9f75c6-a3b5a7897c5b8f9b73dbb419
D/OkHttp: x-cache: Error from cloudfront
D/OkHttp: via: 1.1 0932afdebb722b4465fd681f0h67865a.cloudfront.net (CloudFront)
D/OkHttp: {
D/OkHttp: "message": {
D/OkHttp: "login_credential": "Missing required parameter in the JSON body or the post body or the query string"
D/OkHttp: }
D/OkHttp: }
D/OkHttp: <-- END HTTP (138-byte body)
答案 0 :(得分:0)
通常还会添加@Expose参数,如:
@Expose
@SerializedName("error")
private ApiErrorNew error;
@Expose
@SerializedName("Status")
private String status;
添加相同并尝试。
答案 1 :(得分:0)
我通过在POST请求中添加一些标题来修复此问题:
module.o