首先需要凌空请求响应才能使json对象成为第二个请求

时间:2016-10-05 08:51:04

标签: android json api android-volley multipart

我的排球请求序列存在很大问题,并且第二次请求的第一个请求响应中出现了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发送请求并获取已发布图像的一些信息,然后我需要将这些信息添加到下一篇文章中,以便根据我从第一次发布请求中获得的响应来创建实体。

2 个答案:

答案 0 :(得分:0)

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

    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);

答案 1 :(得分:0)

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变量保存no。成功回应图片上传
  3. 新方法postRequest()调用每个多部分请求响应
  4. postRequest()方法检查是否并非所有响应过程都跳过第二次api调用
  5.   

    另请参阅fb如何执行此批量请求https://developers.facebook.com/docs/android/graph/ - &gt;批量要求

    注意 -

    1. 我已经增加了变量totalSuccesfulImagePost并在每个响应中处理,尽管你需要Response.ErrorListener()

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

    3. 使用ThreadPoolExecutor解决方法

      a)创建ThreadPoolExecutor&amp;初始化最小/最大池大小

      b)将每个mulitpart-request设置为将图像上传到每个线程

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

      d)执行池

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