如何用android排列android中的MVC api?

时间:2017-03-17 08:25:09

标签: android api model-view-controller android-volley

我已经尝试过这段代码,但是第一种方式无效:

String api = "address mvc api";


                StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,api,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.e("tahg" , ""+response);
                            }
                        }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d("volley", "Error: " + error.getMessage());

                    }
                }) {

                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parametr = new HashMap<String, String>();
                        parametr.put("parametr1", "parametr1");
                        parametr.put("parametr2", "parametr2");
                        parametr.put("parametr3", "parametr3");

                        return parametr;
                    }

                };
                RequestQueue  requestqueue = Volley.newRequestQueue(getApplicationContext());
                requestqueue.add(jsonObjRequest);

第二种方式是它也不起作用:

HashMap<String, String> params = new HashMap<String, String>();

                params.put("parametr1", "value1");
                params.put("parametr1", "value2");
                params.put("parametr1", "value3");

                params.put("location2", "0");


                String api = "address api";


                JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, api, new JSONObject(params), new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
                        //do other things with the received JSONObject
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        HashMap<String, String> pars = new HashMap<String, String>();
                        pars.put("Content-Type", "application/json; charset=utf-8");
                        return pars;
                    }


                }
                ;
                //add to the request queue
                RequestQueue  requestqueue = Volley.newRequestQueue(getApplicationContext());
                requestqueue.add(jor);

我应该提到我已经用两种方式尝试了这些内容类型标题:

 1-"application/json"
 2-"application/json; charset=utf-8"
 3-"application/x-www-form-urlencoded"
 4-"application/x-www-form-urlencoded; charset=utf-8"

不幸的是总是遇到这个错误:

Volley: [420] BasicNetwork.performRequest: Unexpected response code 400 for

api地址是:

http://www.api.manelin.com/api/Insert_Advertising

1 个答案:

答案 0 :(得分:0)

这是几年前我遇到的一个项目,我只是想起它,也许可以为您提供帮助:我编写了该类,以使用MVC API上传图像:

import android.graphics.Bitmap;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import static ir.hpbyp.app.industapp.utils.G.context;

/**
 * Created by pc_vahid on 3/28/2016.
 */

public class helperVolley {

    private JsonListner dataRecivedListener;
    private ImageListener ImageListener;

    private Response.ErrorListener volleyErrorListener;

    private String url;

    private String url_place_title;

    /**
     * @param URL
     * @param JsonListner
     */
    public helperVolley(String URL, JsonListner JsonListner) {
        this.url = URL;
        this.dataRecivedListener = JsonListner;

    }

    public helperVolley(String URL, ImageListener imageListener) {
        this.url = URL;
        this.ImageListener = imageListener;

    }


    public void ApiPostMethode(Map<String, String> JSONDATA) {
        final RequestQueue queue = Volley.newRequestQueue(context);
        final JsonObjectRequest jsonSend = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(JSONDATA),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("test", "data :" + response.toString());
                        dataRecivedListener.dataReciver(response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("test", "data error:" + error.toString());
            }
        }
        ) {
            @Override
            public String getPostBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

        };
        jsonSend.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(jsonSend);
    }

    static RequestQueue queue;


    public void ApiGetMethode() {
        queue = Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("test", "data :" + response.toString());
                        dataRecivedListener.dataReciver(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("test", "error :" + error.toString());

            }

        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                100000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

    }

    public static void cancelRequests() {
        queue.cancelAll(new RequestQueue.RequestFilter() {
            @Override
            public boolean apply(Request<?> request) {
                return true;
            }
        });
    }

    public void cancel() {
        if (queue != null) {
            queue.cancelAll(new RequestQueue.RequestFilter() {
                @Override
                public boolean apply(Request<?> request) {
                    return true;
                }
            });
        }

    }


    public void ApiPostMethodeWithError(Map<String, String> JSONDATA, Response.ErrorListener volleyerrorlistener) {
        this.volleyErrorListener = volleyerrorlistener;
        queue = Volley.newRequestQueue(context);
        final JsonObjectRequest jsonSend = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(JSONDATA),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        dataRecivedListener.dataReciver(response.toString());
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("onTextChanged4", error.toString());
            }
        }
        ) {
            @Override
            public String getPostBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

        };
        queue.add(jsonSend);
    }

    public void ApiPostStringRequestWithError(final Map<String, String> JSONDATA, Response.ErrorListener volleyerrorlistener) {

        queue = Volley.newRequestQueue(context);
        StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                dataRecivedListener.dataReciver(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dataRecivedListener.dataReciver(error.toString());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = JSONDATA;
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                // Removed this line if you dont need it or Use application/json
                // params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }

        };
        queue.add(sr);
    }

    public void ApiGetMethodeWithError(Response.ErrorListener volleyerrorlistener) {

        DiskBasedCache cache = new DiskBasedCache(context.getCacheDir(), 16 * 1024 * 1024);
        queue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
        queue.start();
        this.volleyErrorListener = volleyerrorlistener;
        queue = Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("test", "data :" + response.toString());
                        dataRecivedListener.dataReciver(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                volleyErrorListener.onErrorResponse(error);
            }
        });
        queue.add(stringRequest);
    }

    public void GetMethodeObject(final Response.ErrorListener volleyerrorlistener) {
        DiskBasedCache cache = new DiskBasedCache(context.getCacheDir(), 16 * 1024 * 1024);
        queue = new RequestQueue(cache, new BasicNetwork(new HurlStack()));
        queue.start();
        this.volleyErrorListener = volleyerrorlistener;
        queue = Volley.newRequestQueue(context);

            JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.i("test", "data :" + response.toString());
                dataRecivedListener.dataReciver(response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("test", "ERROR :" + error.toString());
                volleyerrorlistener.onErrorResponse(error);

            }
        });
        queue.add(jsonObjReq);

    }


    /**
     * @ this method get the image from the url
     */
    public void LoadImage() {
        ImageRequest request = new ImageRequest(url,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                        ImageListener.ImageRecived(bitmap);
                    }
                }, 0, 0, null,
                new Response.ErrorListener() {
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        queue.add(request);
    }


    public void ApiPostStringRequestWithToken(final Map<String, String> JSONDATA, Response.ErrorListener volleyerrorlistener) {

        queue = Volley.newRequestQueue(context);
        StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                dataRecivedListener.dataReciver(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dataRecivedListener.dataReciver(error.toString());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {

                return JSONDATA;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("authorization", token);
                return params;
            }

            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }
        };
        queue.add(sr);
    }

    public String token = "bearer token"; // you should change this token
}

这是我在上一课中使用的侦听器:

public interface JsonListner {
    /**
     * @param JSON_DATA
     */
    void dataReciver(String JSON_DATA);

}

这是使用辅助截击的示例之一:

 helperVolley helperVolley = new helperVolley("your url", new JsonListner() {
            @Override
            public void dataReciver(String JSON_DATA) {

            }
        });
        helperVolley.ApiGetMethode();