我有很多json Api如何创建方法/接口传递url获取响应

时间:2015-12-29 10:16:22

标签: android android-volley

*如何创建界面使用任何安卓android Json Volley Library请帮帮我*

 public void getJsonRequest(){//Create interface and jsonObjectRequest  
  JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                list =parseJSONRequest(response);// create interface
               adapter.setAllLinks(list);  // create interface
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorJson.setVisibility(View.VISIBLE);
                String map = VolleyErrorException.getErrror(error, getContext());
                errorJson.setText(map);
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

1 个答案:

答案 0 :(得分:0)

这是解决方案。我在一个单独的类APIManager中创建了一个静态方法。

/**
 * The method to create a Request with specific method except GET
 *
 * @param method     The request Method ex. (Request.Method.POST)
 * @param params     The parameters map
 * @param url        The base url of webservice to be called
 * @param requestTag The request Tag to assign when putting request to request queue
 * @param listener   The listener for request completion.
 */
public static void createPostRequest(int method, final Map<String, String> params, String url, String requestTag, final OnRequestCompletedListener listener) {
    JsonObjectRequest request = new JsonObjectRequest(method, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            listener.onRequestCompleted(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onRequestError(getErrorMessageFromVolleyError(error));
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded";
        }

        @Override
        public byte[] getBody() {
            Uri.Builder builder = Uri.parse("http://example.com")
                    .buildUpon();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.appendQueryParameter(entry.getKey(),
                        entry.getValue());
            }
            return builder.build().getEncodedQuery().getBytes();
        }
    };
    AppController.getInstance().addToRequestQueue(request, requestTag);
}

/**
 * The interface for callback when API Request completes.
 */
public interface OnRequestCompletedListener {
    /**
     * The interface method called when API call successfully completes.
     *
     * @param jsonObject The JSONObject recieved from the API call.
     */
    void onRequestCompleted(JSONObject jsonObject);

    /**
     * The interface method called when API call recieves any Error.
     *
     * @param errorMessage The error message
     */
    void onRequestError(String errorMessage);
}

/**
 * The method to convert volley error into user readable string message.
 *
 * @param error The volleyError recieved during API call
 * @return The String containing the message related to error
 */
public static String getErrorMessageFromVolleyError(VolleyError error) {

    if (error instanceof TimeoutError) {
        return AppController.getContext().getString(R.string.time_out_error_message);
    }

    if (error instanceof NoConnectionError) {
        return AppController.getContext().getString(R.string.no_connection_error_message);
    }

    if (error instanceof ServerError) {
        return AppController.getContext().getString(R.string.server_error_message);
    }

    if (error instanceof NetworkError) {
        return AppController.getContext().getString(R.string.network_error_message);
    }

    if (error instanceof ParseError) {
        return AppController.getContext().getString(R.string.parse_error_message);
    }
    return null;
}

要调用此方法,请在任何活动或片段类中使用它,就像这样。

private void getEvaultFiles() {
        Map<String, String> params = new HashMap<>();
        params.put("EvaultId", item.id);
        APIManager.createPostRequest(Request.Method.POST,params, AppConstants.GET_EVAULT_FILES_URL, "GETEVAULTFILES", new APIManager.OnRequestCompletedListener() {
            @Override
            public void onRequestCompleted(JSONObject jsonObject) {
                Utils.hideProgressAndShowContent(EvaultDetailActivity.this);
                listFiles.clear();
                tvEmpty.setText("No Files to display");
                try {
                    JSONArray files = jsonObject.getJSONObject("Result").getJSONArray("Files");
                    for (int i = 0; i < files.length(); i++) {
                        EvaultFile file = new EvaultFile();
                        JSONObject temp = files.getJSONObject(i);
                        file.name = temp.getString("FileName");
                        file.size = temp.getString("FileSize");
                        file.fileurl = temp.getString("FilePathFullImage");
                        listFiles.add(file);
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRequestError(String errorMessage, JSONObject data) {


            }
        });
    }