解析来自 volley 的请求

parsing request from volley

我有一个奇怪的问题,我向服务器发出了一个简单的请求,它成功响应,我解析它没有问题,然后我将从服务器返回的值分配给我的响应模型 class 但没有出现尽管我在日志文件中找到了所有值,但它们都是空值: (提示:大部分回复是阿拉伯语)

这是我的响应模型 class:

    public class QuestionResponse {
        private String lang,questionID,question,choiceOne,choiceTwo,choiceThree,
                type;

        public QuestionResponse(){}

        public QuestionResponse(String lang, String questionID, String question, 
                                String choiceOne, String choiceTwo, String choiceThree, String type) {
            this.lang = lang;
            this.questionID = questionID;
            this.question = question;
            this.choiceOne = choiceOne;
            this.choiceTwo = choiceTwo;
            this.choiceThree = choiceThree;
            this.type = type;
        }

        public String getLang() {
            return lang;
        }

        public void setLang(String lang) {
            this.lang = lang;
        }

        public String getQuestionID() {
            return questionID;
        }

        public void setQuestionID(String questionID) {
            this.questionID = questionID;
        }

        public String getQuestion() {
            return question;
        }

        public void setQuestion(String question) {
            this.question = question;
        }

        public String getChoiceOne() {
            return choiceOne;
        }

        public void setChoiceOne(String choiceOne) {
            this.choiceOne = choiceOne;
        }

        public String getChoiceTwo() {
            return choiceTwo;
        }

        public void setChoiceTwo(String choiceTwo) {
            this.choiceTwo = choiceTwo;
        }

        public String getChoiceThree() {
            return choiceThree;
        }

        public void setChoiceThree(String choiceThree) {
            this.choiceThree = choiceThree;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }

这是我的请求方法:

public QuestionResponse getQuestion(){

        String BaseUrl = "http://winnerten.com/wini/public/api/";
        String finalUrl = BaseUrl+"get-question";
        final String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQwYzZiMDliNDQ5NjczNDUzYzNkYTY5OWUyZGY1NTI3ZjkxZTY4MDMifQ.eyJhenAiOiIyNTIyMTAyMDMyOTYtbWw5amRicmswaDJodGVicWRtdW9mNzRyaHZ1NDk1ZGwuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyNTIyMTAyMDMyOTYtZjdvMHU5OGt2bjVvZjhsYXZ1cnB0dHYwNzRwMDVqNzMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMTU2NDMyMjIzNjQ5Njc1OTY2NDIiLCJlbWFpbCI6ImZhdGVtYWFobWVkMTk1M0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZXhwIjoxNTMzMTIyMjQyLCJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJpYXQiOjE1MzMxMTg2NDIsIm5hbWUiOiJmYXRlbWEgYWhtZWQiLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDQuZ29vZ2xldXNlcmNvbnRlbnQuY29tLy13c0FPMWlpTUFYMC9BQUFBQUFBQUFBSS9BQUFBQUFBQUFBQS9BQW5uWTdwTG9PSlptNXU1V2F5YmlYRGhGQnktSy1xRzNRL3M5Ni1jL3Bob3RvLmpwZyIsImdpdmVuX25hbWUiOiJmYXRlbWEiLCJmYW1pbHlfbmFtZSI6ImFobWVkIiwibG9jYWxlIjoiZW4ifQ.HSqzBnGOEw9j33gnIiHycaAb8MPwaq7Elh94D9yBFrTABaOtLL9TNQxX4v7AeyWMRFApFrXw9F0lLfh7khH4dPSwTWKe8dnBJYvlUs_mGHP0tk0VuNr4fNhMWVgbRnn6EnfCUtLRHimXmPCJXJW8NVPtGuNWH5clifC-BbIYgQgXorMW9TCROmBUVj6E-kP023zFvhTHzbrcs7aNq8hx0P30gwyrbnyyWpfCUGG0Q5n5GmaF8onEkMjWx7Z-ZC4UsFSFECzf2Pj9ydB9K3FRUkYO0XZIyRtURZLNs8f6zbB6e0jjw26ETugUVqHTFYvoUcJeWwHK9Axuz9ZuBCeeww";

        final QuestionResponse ques= new QuestionResponse();
        RequestQueue queue = Volley.newRequestQueue(this);

        StringRequest postRequest = new StringRequest(Request.Method.POST, finalUrl,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("ques.response",response);
                        try {
                            JSONObject all = new JSONObject(response);
                            JSONObject data = all.getJSONObject("data");
                            questionId = String.valueOf(data.getInt("questions_id"));
                            type = data.getString("type");

                            ques.setQuestionID(String.valueOf(data.getInt("questions_id")));
                            ques.setType(data.getString("type"));
                            Log.d("id",questionId);
                            Log.d("type",type);
                            if(type.equals("multi")){
                                question = data.getString("question");
                                choiceOne = data.getString("choice_1");
                                choiceTwo = data.getString("choice_2");
                                choiceThree = data.getString("choice_3");
                                lang = data.getString("lang");

                                ques.setQuestion(data.getString("question"));
                                ques.setChoiceOne(data.getString("choice_1"));
                                ques.setChoiceTwo(data.getString("choice_2"));
                                ques.setChoiceThree(data.getString("choice_3"));
                                ques.setLang(data.getString("lang"));

                                Log.d("question",question);
                                Log.d("ch_1",choiceOne);
                                Log.d("ch_2",choiceTwo);
                                Log.d("ch_3",choiceThree);
                                Log.d("type",type);
                            }
                            else if(type.equals("image")){
                                question = data.getString("question");
                                choiceOne = data.getString("choice_1");
                                choiceTwo = data.getString("choice_2");
                                choiceThree = data.getString("choice_3");
                                lang = data.getString("lang");

                                ques.setQuestion(data.getString("question"));
                                ques.setChoiceOne(data.getString("choice_1"));
                                ques.setChoiceTwo(data.getString("choice_2"));
                                ques.setChoiceThree(data.getString("choice_3"));
                                ques.setLang(data.getString("lang"));
                            }
                            else if(type.equals("correct")){
                                question = data.getString("question");
                                choiceOne = data.getString("choice_1");
                                choiceTwo = data.getString("choice_2");
                                choiceThree = data.getString("choice_3");
                                lang = data.getString("lang");

                                ques.setQuestion(data.getString("question"));
                                ques.setChoiceOne(data.getString("choice_1"));
                                ques.setChoiceTwo(data.getString("choice_2"));
                                ques.setChoiceThree("");
                                ques.setLang(data.getString("lang"));

                            }
                            Log.d("ques.parse.done","question parsing done");

                        } catch (JSONException e) {
                            Log.d("ques.parsing.error","parsing failed");
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        Log.d("ques.error.response",error.toString());
                    }
                }
        ){
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<String, String>();
                params.put("token", token);
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImNlMDU4OGM4MmJiYjMwOGFjNTk1NWY3ZWVhMDI3ODVlYmM0NzkyZjFjY2ZmN2JjNzdkYmE3YjJmYjM5YjNiMThlMTY2NjgxZTQ0NTBmMWY4In0.eyJhdWQiOiIxIiwianRpIjoiY2UwNTg4YzgyYmJiMzA4YWM1OTU1ZjdlZWEwMjc4NWViYzQ3OTJmMWNjZmY3YmM3N2RiYTdiMmZiMzliM2IxOGUxNjY2ODFlNDQ1MGYxZjgiLCJpYXQiOjE1MzI3NzgwMjgsIm5iZiI6MTUzMjc3ODAyOCwiZXhwIjoxNTY0MzE0MDI4LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.EdebRxSgPIjU74xyqZFI-HqAjQJlmICaCNohRQNEK4LG4t3aIOAdna1J4IlZbmX-LXc7NxrMpXtOUs9Ino9OPN6IOBqL1exG57hLdvzQLlBxyagtsa4OKhZLdWIkD_DlZCepalNjg2q9TN1SIb6INihaVHWr-cxWu3jy4I_1IO-hrJmGox_M2lpvF-gMKd5TRoS9nLSSOfXMG9kdkRu5sV0l4DHViq7DylLivfiP_xoCq67AzBGqwqQqQwx7UBjQYF0QcdDJOzmCm4xiSFGpDZJKww8V8xHkCTesD-k3Zmc5Mqx5M-COO_8dewsP2ifLyRbKN8m8gOqVhrJlT1Rgkb71bYsCISMQ3QzFk2Y6ju_bxdiHDSrs99wlK4GxfmqAtBuzFXkamw7P0Ay-hwzPEg2rV0M7Ui2F9e9wNKkVmibBxyPIzHSEGpNF_lNG1TJbmhAHwngZh17TwhOLqTXV71nDJpKFzQgX1dTGC4ORtlMVEgpbGlDDfH0hY51qDUp7t-c4Egsue8nI1uyQ-CBiste1bGCBlpCkG-6WEEoYcQ1l4zJLmYu_VrR82ROEkgNFYQ4seck90s_iP2_tZr8GoiTmwFdIHui95pFBceTZIFQNvQ6jwJeo58jjB7-Ye-JvmyPm59FQm5Vigy-nEsvfuOCE7wxcrGh9qx--wOvfYQs");
                headers.put("Accept", "application/json");
                return headers;
            }
        };


        // handles the slow connection, i.e connection timeout //
        //int socketTimeout = 5000;  //5 seconds
        int socketTimeout = 30000; // 30 seconds. You can change it
        RetryPolicy policy = new DefaultRetryPolicy(
                socketTimeout,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

        postRequest.setRetryPolicy(policy);
        queue.add(postRequest);

        return ques;
    }

这是我的响应日志文件:

08-09 13:35:51.931 6077-6077/com.example.nasrmohamed.testapi10 D/ques.response: {"data":{"questions_id":55,"created_at":"2018-08-08 14:42:28","updated_at":"2018-08-08 14:42:28","question":"\u0645\u0627\u0647\u0649 \u0627\u0644\u0633\u0644\u0633\u0644\u0629 \u0627\u0644\u0645\u0643\u0648\u0646\u0629 \u0645\u0646 \u0639\u0638\u0627\u0645 \u0648\u063a\u0636\u0627\u0631\u064a\u0641 \u0648\u0627\u0644\u062a\u0649 \u062a\u0645\u062a\u062f \u0645\u0646 \u0627\u0644\u062c\u0645\u062c\u0645\u0629 \u0627\u0644\u0649 \u0627\u0644\u0639\u0635\u0639\u0635\u061f","choice_1":"\u0627\u0644\u0642\u0641\u0635 \u0627\u0644\u0635\u062f\u0631\u0649","choice_2":"\u0627\u0644\u0647\u064a\u0643\u0644 \u0627\u0644\u0639\u0638\u0645\u0649","choice_3":"\u0627\u0644\u0639\u0645\u0648\u062f \u0627\u0644\u0641\u0642\u0631\u0649","type":"multi","lang":"ar"},"code":200}

对于 Volley 只做简单的

第一步:-创建gson对象。

Gson gson = new GsonBuilder().create();

第 2 步:-Filled/Store 对模型文件的响应

ModelFile modelFile= gson.fromJson(YOUR_RESPONSE_STRING, ModelFile .class);

第 3 步:- 检查数据。

进行调试并检查响应数据是否已填充到您的模型中

是的,因为 "ques" 在设置响应中的值之前返回。

尝试在此方法中设置您的 "ques" 值

              @Override
                public void onResponse(String response) {
                   //set your values here in the adapter
                   }

看起来问题是您立即从 getQuestion 函数 return ques,但是发送请求和获得响应需要一些时间。所以当你 return ques 它还没有被解析。

您可以通过向 getQuestion 函数传递一个回调对象来解决该问题,该回调对象将在请求实际 return 时调用。像这样:

public class ResponseHandler {

    public void HandleReturnedQuestionResponse(QuestionRepsponse ques) {
        // Do stuff when the response has returned 
    }

}


public QuestionResponse getQuestion(ResponseHandler responseHandler) {

    // ...

    StringRequest postRequest = new StringRequest(Request.Method.POST, finalUrl,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {

                        // ... parse reponse ...

                        responseHandler.HandleReturnedQuestionResponse(ques)
                    }
}

// Usage:
getQuestion(new ResponseHandler())

试试这个代码..

public class Data{

@SerializedName("updated_at")
private String updatedAt;

@SerializedName("question")
private String question;

@SerializedName("questions_id")
private int questionsId;

@SerializedName("choice_2")
private String choice2;

@SerializedName("created_at")
private String createdAt;

@SerializedName("choice_3")
private String choice3;

@SerializedName("type")
private String type;

@SerializedName("lang")
private String lang;

@SerializedName("choice_1")
private String choice1;

public void setUpdatedAt(String updatedAt){
    this.updatedAt = updatedAt;
}

public String getUpdatedAt(){
    return updatedAt;
}

public void setQuestion(String question){
    this.question = question;
}

public String getQuestion(){
    return question;
}

public void setQuestionsId(int questionsId){
    this.questionsId = questionsId;
}

public int getQuestionsId(){
    return questionsId;
}

public void setChoice2(String choice2){
    this.choice2 = choice2;
}

public String getChoice2(){
    return choice2;
}

public void setCreatedAt(String createdAt){
    this.createdAt = createdAt;
}

public String getCreatedAt(){
    return createdAt;
}

public void setChoice3(String choice3){
    this.choice3 = choice3;
}

public String getChoice3(){
    return choice3;
}

public void setType(String type){
    this.type = type;
}

public String getType(){
    return type;
}

public void setLang(String lang){
    this.lang = lang;
}

public String getLang(){
    return lang;
}

public void setChoice1(String choice1){
    this.choice1 = choice1;
}

public String getChoice1(){
    return choice1;
}

@Override
public String toString(){
    return 
        "Data{" + 
        "updated_at = '" + updatedAt + '\'' + 
        ",question = '" + question + '\'' + 
        ",questions_id = '" + questionsId + '\'' + 
        ",choice_2 = '" + choice2 + '\'' + 
        ",created_at = '" + createdAt + '\'' + 
        ",choice_3 = '" + choice3 + '\'' + 
        ",type = '" + type + '\'' + 
        ",lang = '" + lang + '\'' + 
        ",choice_1 = '" + choice1 + '\'' + 
        "}";
    }
    }

响应数据..

public class ResponseData{

@SerializedName("code")
private int code;

@SerializedName("data")
private Data data;

public void setCode(int code){
    this.code = code;
}

public int getCode(){
    return code;
}

public void setData(Data data){
    this.data = data;
}

public Data getData(){
    return data;
}

@Override
public String toString(){
    return 
        "Response{" + 
        "code = '" + code + '\'' + 
        ",data = '" + data + '\'' + 
        "}";
    }
   }

将以下依赖项添加到应用级别 gradle 文件..

   implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

创建改装对象..

public class ApiClient {
private final static String BASE_URL = "https://api.github.com"; // define your url..

public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
}

api 打电话..

public interface ApiInterface {
@GET("path")
Call<ResponseData> getUserData();
}

api 调用 activity..

 Call<ResponseData> dataCall=apiInterface.getUserData();
    dataCall.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
            if (response!=null && response.isSuccessful() && response.body()!=null){

            }
            else{
                if (response.errorBody()!=null){
                    ErrorResponse errorResponse=new Gson().fromJson(response.errorBody().toString(),ErrorResponse.class);
                    Log.d("Error data",response.errorBody().toString());
                }
            }
        }

        @Override
        public void onFailure(Call<ResponseData> call, Throwable t) {

        }
    });