【问题标题】:need first volley request response to make json object for second request需要第一个凌空请求响应来为第二个请求生成 json 对象
【发布时间】:2016-10-05 08:51:04
【问题描述】:

我对 volley 请求序列和从第二个请求的第一个请求响应中制作 json 数组有一个大问题。

这是代码:

    JSONObject imageAddedResponse = new JSONObject();
    JSONArray imagesAddedResponse = new JSONArray();

public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {

    //Instantiate the RequestQueue.
    RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);

    Settings settings = new Settings(applicationContext);
    String selectedURL = settings.getChosenUrl();
    final String token = settings.getTokenKey();
    String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("Authorization", "Bearer " + token);
    params.put("Content-Disposition", "form-data" + "; charset=utf-8");

    //POST data to CMS to get JSONObject back
    for (int i = 0; i < mImages.size(); i++) {
        String path = String.valueOf(mImages.get(i).getPath());
        File file = new File(path);
            MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (listener != null) {
                        listener.onAPIPostData(String.valueOf(response), true);
                    }
                    if (response != null || response != "") {
                        try {
                            imageAddedResponse = new JSONObject(response);
                            JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
                            JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
                            imagesAddedResponse.put(jsonArrayImages);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley Request Error", error.toString());
                    if (listener != null) {
                        listener.onAPIPostData("", false);
                    }
                }
            });
            requestQueue.add(request);
    }

    //POST request to add entity to CMS
    JSONObject jsonimages = new JSONObject();
    JSONArray jsonArrayimages = new JSONArray();
    for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
        try {
            JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
            jsonimages.put("id",getObjectValues.getString("id"));
            jsonimages.put("src",getObjectValues.getString("src"));
            jsonimages.put("size",getObjectValues.getString("size"));
            jsonimages.put("baseName",getObjectValues.getString("baseName"));
            jsonimages.put("type",getObjectValues.getString("type"));
            jsonimages.put("db_languages_id", "1");
            jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));              
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    JSONObject json = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    JSONObject finalobject = new JSONObject();
    try {
        json.put("title", title);
        json.put("description", note);
        json.put("db_languages_id", "1");
        json.put("db_user_id", "3");
        jsonArray.put(json);
        finalobject.put("data", jsonArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
    JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            // response
            if (listener != null) {
                listener.onAPIPostData(String.valueOf(response), true);
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    if (listener != null) {
                        listener.onAPIPostData("", false);
                    }
                }
            }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Authorization", "Bearer " + token);
            params.put("Content-Type", "application/json; charset=utf-8");
            return params;
        }
    };
    postRequest.setShouldCache(false);
    requestQueue.add(postRequest);
}

首先请求发布到 CMS 并获取发布的图像的一些信息,然后我需要将这些信息添加到下一个帖子,以根据我从第一次发布请求返回的响应来制作实体。

【问题讨论】:

  • @Angad Tiwari 这个问题
  • 是的...明白了... :-)
  • @saeid 让我明白这一点。 1.您为每个上传到服务器的图像调用 MultiPartRequest(我认为这是一个扩展 Request 的自定义类)。 2. 每次成功将图片上传到服务器后,您都会收到 imp 数据的响应。 3.图片上传成功后,需要调用JsonObjectRequest。这是你想要达到的目标吗?
  • @Angad Tiwari ...你是对的,这是程序,在第二次你提到我得到 json 响应之后,我需要从该响应中为下一个请求制作另一个 jsonarray
  • 检查您的邮件

标签: android json api android-volley multipart


【解决方案1】:
int totalSuccesfulImagePost = 0; //this variable increment when each succesful response from multipart-request

public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {

      //Instantiate the RequestQueue.
      RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);

      Settings settings = new Settings(applicationContext);
      String selectedURL = settings.getChosenUrl();
      final String token = settings.getTokenKey();
      String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
      HashMap<String, String> params = new HashMap<String, String>();
      params.put("Authorization", "Bearer " + token);
      params.put("Content-Disposition", "form-data" + "; charset=utf-8");

      //POST data to CMS to get JSONObject back
      for (int i = 0; i < mImages.size(); i++) {
          String path = String.valueOf(mImages.get(i).getPath());
          File file = new File(path);
          MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (listener != null) {
                    listener.onAPIPostData(String.valueOf(response), true);
                }
                if (response != null || response != "") {
                    try {
                        imageAddedResponse = new JSONObject(response);
                        JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
                        JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
                        imagesAddedResponse.put(jsonArrayImages.getJSONObject(0));
                        totalSuccesfulImagePost++; //here we increase the count
                        postRequest(token); //call this method and check wheather all the image uploaded or not

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley Request Error", error.toString());
                if (listener != null) {
                    listener.onAPIPostData("", false);
                }
            }
        });
        requestQueue.add(request);
   }
}

//make this as seperate method and call when all multipart-request call succesful
public void postRequest(String token){

    if(totalSuccesfulImagePost != mImages.size()) {
        //this means not all the images posted yet, hence return the method
        return;
    }

    //POST request to add entity to CMS
    JSONObject jsonimages = new JSONObject();
    JSONArray jsonArrayimages = new JSONArray();
    for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
        try {
        JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
        jsonimages.put("id",getObjectValues.getString("id"));
        jsonimages.put("src",getObjectValues.getString("src"));
        jsonimages.put("size",getObjectValues.getString("size"));
            jsonimages.put("baseName",getObjectValues.getString("baseName"));
            jsonimages.put("type",getObjectValues.getString("type"));
            jsonimages.put("db_languages_id", "1");
            jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));              
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    JSONObject json = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    JSONObject finalobject = new JSONObject();
    try {
        json.put("title", title);
        json.put("description", note);
        json.put("db_languages_id", "1");
        json.put("db_user_id", "3");
        jsonArray.put(json);
        finalobject.put("data", jsonArray);
    } catch (JSONException e) {
        e.printStackTrace();.getJSONObject(0)
    }
    String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
    JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            // response
            if (listener != null) {
                listener.onAPIPostData(String.valueOf(response), true);
            }
        }
    },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                if (listener != null) {
                    listener.onAPIPostData("", false);
                }
            }
        }
) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("Authorization", "Bearer " + token);
        params.put("Content-Type", "application/json; charset=utf-8");
        return params;
    }
};
    postRequest.setShouldCache(false);
    requestQueue.add(postRequest);
}

更新了您的代码。希望这对您有所帮助。

  1. 我为 JsonObjectRequest 创建了名为 postRequest() 的新方法;
  2. totalSuccesfulImagePost 变量保存编号。图片上传成功率
  3. 新方法 postRequest() 在每个多部分请求响应中调用
  4. postRequest() 方法检查是否不是所有响应过程而不是跳过第二个 api 调用

另请参阅 fb 如何执行此批处理请求 https://developers.facebook.com/docs/android/graph/ -> Batch Reqest

注意-

  1. 我已经在每个响应中增加了变量 totalSuccesfulImagePost 和句柄,尽管您需要 Response.ErrorListener()

  2. 虽然您可以使用 ThreadPoolExecutor 选项,在该选项中创建每个线程来处理每个多部分请求上传并在所有线程执行后调用方法 postRequest()

使用 ThreadPoolExecutor 的解决方法

a) 创建 ThreadPoolExecutor 并初始化最小/最大池大小

b) 分配每个多部分请求以将图像上传到每个线程

c) 将所有线程(包含图片上传多部分请求)添加到 ThreadPoolExecutor

d) 执行池

e) 当 ThreadPoolExecutor 为空时调用 postRequest() 方法,即这意味着所有线程执行完成并准备调用 postRequest()

【讨论】:

    【解决方案2】:

    可以使用每个请求的优先级。

        private Priority priority = Priority.HIGH;
    
    StringRequest strReq = new StringRequest(Method.GET,
                Const.URL_STRING_REQ, new Response.Listener<String>() {
    
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, response.toString());
                        msgResponse.setText(response.toString());
                        hideProgressDialog();
    
                    }
                }, new Response.ErrorListener() {
    
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hideProgressDialog();
                    }
                }) {
            @Override
            public Priority getPriority() {
                return priority;
            }
    
        };
    
        MyApplication.getInstance().addToRequestQueue(strReq);
    

    【讨论】:

    • 谢谢你的回答@sathish gadde ...你能解释一下吗,到目前为止这对我没有帮助
    猜你喜欢
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    相关资源
    最近更新 更多