onResponse 函数中的改进响应 return null(单个 JSON 对象)
Retrofit response return null in onResponse function (single JSON object)
我尝试在注册用户后从改装 API 中获得响应。
我从 response.body()
函数
中得到 null
注册URL:https://apitest10101.000webhostapp.com/alaa-apii/public/createuser(方法POST)
API return 单个对象 JSON 喜欢
{
"error": true,
"message": "User Already Exists"
}
"response work after tested in postman"
RegisterActivity.java
public void register(View view) {
if(Validate())
{
Log.d("####", "OKAAAAAY");
first_name = first_name_edit.getText().toString().trim();
last_name = last_name_edit.getText().toString().trim();
email = email_edit.getText().toString().trim();
password = password_edit.getText().toString().trim();
phone = Integer.parseInt(phone_edit.getText().toString().trim());
state = state_edit.getText().toString().trim();
block = block_edit.getText().toString().trim();
street = street_edit.getText().toString().trim();
building = buidling_edit.getText().toString().trim();
floor = floor_edit.getText().toString().trim();
flat = flat_edit.getText().toString().trim();
Call<ResultModel> call = RetrofitClient
.getInstance()
.getApi()
.createUser(first_name, last_name, email, password, phone, postionOfReigon, state, block, street, building, floor, flat);
call.enqueue(new Callback<ResultModel>() {
@Override
public void onResponse(Call<ResultModel> call, Response<ResultModel> response) {
boolean error = false;
String mass = null;
if (response.body() != null) { // response null !!!!!!!!!!!
error = response.body().getError();
mass = response.body().getMessage();
Log.d("#####", error + "------" + mass);
}
Log.d("#####", error + "------" + mass);
}
@Override
public void onFailure(Call<ResultModel> call, Throwable t) {
Toast.makeText(RegisterActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
else
{
Log.d("####", "NNNOOTT OKAAAAAY");
}
}
如果我删除 response.body()
中的 if 语句,我会在日志
中收到此错误
2019-11-10 12:45:51.242 21211-21211/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 21211
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.example.myapplication.ResultModel.getError()' on a null object reference
at com.example.myapplication.RegisterActivity.onResponse(RegisterActivity.java:161)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall.run(DefaultCallAdapterFactory.java:83)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
ResultModel.java
package com.example.myapplication;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResultModel {
@SerializedName("error")
@Expose
private Boolean error;
@SerializedName("message")
@Expose
private String message;
public ResultModel(Boolean error, String message) {
this.error = error;
this.message = message;
}
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
RetrofitClient.java
package com.example.myapplication;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static final String BASE_URL = "https://apitest10101.000webhostapp.com/alaa-apii/public/";
private static RetrofitClient mInstance;
private Retrofit retrofit;
private RetrofitClient(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance()
{
if(mInstance == null)
{
mInstance = new RetrofitClient();
}
return mInstance;
}
public Api getApi()
{
return retrofit.create(Api.class);
}
}
API接口
package com.example.myapplication;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Api {
@FormUrlEncoded
@POST("createuser")
Call<ResultModel> createUser(
@Field("firstname") String firstname,
@Field("lastname") String lastname,
@Field("email") String email,
@Field("password") String password,
@Field("phone") int phone,
@Field("region") int region,
@Field("state") String state,
@Field("block") String block,
@Field("street") String street,
@Field("building") String building,
@Field("floor") String floor,
@Field("flat") String flat
);
}
建设gradle
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
getError()
应该 return false or true 和 getMessage()
应该 return 消息 User Already Exists 或 User created successfully .
我使用slim framework v3.12搭建api.
** 任何建议 **
您似乎获得 422
作为 http 状态。所有不是 2XX
状态代码的内容都被改造视为错误,在这种情况下,您可以使用 response.errorBody()
.
访问它
不太好的消息是它必须手动转换。一种方法是使用 response.errorBody().string()
.
确保只调用一次,因为第一次读取后它将不再可读。这是一种流式行为。
您得到的响应代码是 422,如果后端和前端同意此代码不是错误,那么您可以通过创建自定义 Interceptor
并让它保持 return 当您获得该响应代码时得到的响应,只需确保将 Interceptor
添加到您的 Retrofit client
我尝试在注册用户后从改装 API 中获得响应。
我从 response.body()
函数
注册URL:https://apitest10101.000webhostapp.com/alaa-apii/public/createuser(方法POST)
API return 单个对象 JSON 喜欢
{
"error": true,
"message": "User Already Exists"
}
RegisterActivity.java
public void register(View view) {
if(Validate())
{
Log.d("####", "OKAAAAAY");
first_name = first_name_edit.getText().toString().trim();
last_name = last_name_edit.getText().toString().trim();
email = email_edit.getText().toString().trim();
password = password_edit.getText().toString().trim();
phone = Integer.parseInt(phone_edit.getText().toString().trim());
state = state_edit.getText().toString().trim();
block = block_edit.getText().toString().trim();
street = street_edit.getText().toString().trim();
building = buidling_edit.getText().toString().trim();
floor = floor_edit.getText().toString().trim();
flat = flat_edit.getText().toString().trim();
Call<ResultModel> call = RetrofitClient
.getInstance()
.getApi()
.createUser(first_name, last_name, email, password, phone, postionOfReigon, state, block, street, building, floor, flat);
call.enqueue(new Callback<ResultModel>() {
@Override
public void onResponse(Call<ResultModel> call, Response<ResultModel> response) {
boolean error = false;
String mass = null;
if (response.body() != null) { // response null !!!!!!!!!!!
error = response.body().getError();
mass = response.body().getMessage();
Log.d("#####", error + "------" + mass);
}
Log.d("#####", error + "------" + mass);
}
@Override
public void onFailure(Call<ResultModel> call, Throwable t) {
Toast.makeText(RegisterActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
else
{
Log.d("####", "NNNOOTT OKAAAAAY");
}
}
如果我删除 response.body()
中的 if 语句,我会在日志
2019-11-10 12:45:51.242 21211-21211/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 21211
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.example.myapplication.ResultModel.getError()' on a null object reference
at com.example.myapplication.RegisterActivity.onResponse(RegisterActivity.java:161)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall.run(DefaultCallAdapterFactory.java:83)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
ResultModel.java
package com.example.myapplication;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResultModel {
@SerializedName("error")
@Expose
private Boolean error;
@SerializedName("message")
@Expose
private String message;
public ResultModel(Boolean error, String message) {
this.error = error;
this.message = message;
}
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
RetrofitClient.java
package com.example.myapplication;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static final String BASE_URL = "https://apitest10101.000webhostapp.com/alaa-apii/public/";
private static RetrofitClient mInstance;
private Retrofit retrofit;
private RetrofitClient(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance()
{
if(mInstance == null)
{
mInstance = new RetrofitClient();
}
return mInstance;
}
public Api getApi()
{
return retrofit.create(Api.class);
}
}
API接口
package com.example.myapplication;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Api {
@FormUrlEncoded
@POST("createuser")
Call<ResultModel> createUser(
@Field("firstname") String firstname,
@Field("lastname") String lastname,
@Field("email") String email,
@Field("password") String password,
@Field("phone") int phone,
@Field("region") int region,
@Field("state") String state,
@Field("block") String block,
@Field("street") String street,
@Field("building") String building,
@Field("floor") String floor,
@Field("flat") String flat
);
}
建设gradle
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
getError()
应该 return false or true 和 getMessage()
应该 return 消息 User Already Exists 或 User created successfully .
我使用slim framework v3.12搭建api.
** 任何建议 **
您似乎获得 422
作为 http 状态。所有不是 2XX
状态代码的内容都被改造视为错误,在这种情况下,您可以使用 response.errorBody()
.
不太好的消息是它必须手动转换。一种方法是使用 response.errorBody().string()
.
确保只调用一次,因为第一次读取后它将不再可读。这是一种流式行为。
您得到的响应代码是 422,如果后端和前端同意此代码不是错误,那么您可以通过创建自定义 Interceptor
并让它保持 return 当您获得该响应代码时得到的响应,只需确保将 Interceptor
添加到您的 Retrofit client