【发布时间】:2019-10-30 17:18:38
【问题描述】:
我是第一次使用 Retrofit,在登录验证后我运行我的改造 api 调用函数loginApiCall 来验证用户。
即使我的验证错误(电子邮件和密码错误),我也收到了响应 200,但得到了此检查的真实结果 response.isSuccessful() 作为响应。
private void loginApiCall() {
Call<LoginResponse> call = RetrofitClient
.getInstance().getApi().userLogin("*******@gmail.com", "****");
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful())
Toast.makeText(LoginScreen.this, "Success", Toast.LENGTH_SHORT).show();
else
Toast.makeText(LoginScreen.this, "no Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(LoginScreen.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
此处为我的通话进行改造设置
public class RetrofitClient {
private static RetrofitClient mInstance;
private Retrofit retrofit;
private RetrofitClient() {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
public static synchronized RetrofitClient getInstance() {
if (mInstance == null) {
mInstance = new RetrofitClient();
}
return mInstance;
}
public QareebApiInterface getApi() {
return retrofit.create(QareebApiInterface.class);
}
这里是 POST 接口
public interface QareebApiInterface {
@FormUrlEncoded
@POST(WebServiceConstant.END_POINT_NEW_USER)
Call<LoginResponse> userLogin(
@Field("email") String email,
@Field("password") String password
);
}
这里是与改造相关的 gradle 文件
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
我已将 volley call 转换为仅将用户名和密码发送到服务器的改造(没有 Auth)。因为我没有发送或丢失任何东西,所以有任何身份验证问题吗?但是如果缺少为什么响应是 200?
接下来是我用改造取代的凌空呼叫(工作正常)。
public void loginApiCall(final String email, final String password) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, BASE_URL,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: "+response);
}
},
new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
}
【问题讨论】:
-
您确定登录 api 按预期工作吗?你有一个没有做任何事情的拦截器,你可以删除它。
-
@takecare api 在其他应用程序中运行良好,我只是将其转换为改造
-
您是否希望以 Json 的身份响应?你检查过 LoginResponse 类中的 seriliazedName 吗?
-
@Beyazidy 为什么我们需要序列化字符串名称(用户名和密码)?我不认为我们需要它。不是吗?
-
您的帖子参数用户名和密码。但是您以 LoginResponse 的形式获取数据
标签: android android-volley retrofit2