如何使用post方法

时间:2017-09-18 09:57:58

标签: android json android-volley

我有一个使用凌空集成的应用程序。现在我正在进行维护,因为我希望将数据作为数组列表发送,并使用逗号分隔值,如{" cart_details":[3,1]}。所以任何人都可以告诉我如何做到这一点。

我试过这个

 RequestQueue queue1 = Volley.newRequestQueue(CartDetails.this);

            // Request a string response from the provided URL.
            StringRequest stringRequest = new StringRequest(Request.Method.POST, cartDetails+"/cartToBuy",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // your response
                            Log.e("Error response","Error response"+response);
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.e("Error cart","Error Cart"+error.getCause());
                }
            }){



                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    SharedPreferences pref = activity.getSharedPreferences("UserData", Context.MODE_APPEND);
                    String token = pref.getString("userID", "");
                    headers.put(BuildConfig.API_HEADER, BuildConfig.API_HEADER_VALUE);
                    headers.put("USER-ID", token);
                    return headers;
                }
                @Override
                public byte[] getBody() throws AuthFailureError {
                    String your_string_json = cartIdVal; // put your json
                    Log.e("json..","json.."+your_string_json);
                    return your_string_json.getBytes();
                }
            };
            // Add the request to the RequestQueue.
            queue1.add(stringRequest);
         // requestQueue.start();

当我发送这样的数据时,它会抛出201错误。对不起基本问题。我没有那么多意识到凌空。请帮我解决这个问题。

提前致谢。

1 个答案:

答案 0 :(得分:0)

只需创建一个volleyJsonRequestclass,其中包含:

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class VolleyJSonRequest {

    public void MakeJsonRequest(final String Tag, String url, final ArrayList<RequestModel> list, final ResponceLisnter responceLisnter, final String HeaderKey) {

        Map<String, String> params = new HashMap<String, String>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                //MyLog.ShowLog(list.get(i).getKey(), list.get(i).getValue());
                params.put(list.get(i).getKey(), list.get(i).getValue());

            }
        }
        JSONObject obj = new JSONObject(params);
        JsonArrayRequest jsObjRequest = new JsonArrayRequest
                (Request.Method.POST, url, obj, new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        try {
//                            Iterator x = response.keys();
//                            JSONArray jsonArray = new JSONArray();
//
//                            while (x.hasNext()){
//                                String key = (String) x.next();
//                                jsonArray.put(response.get(key));
//                            }
                            responceLisnter.getResponce(response.toString(), Tag);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(com.android.volley.VolleyError error) {
                        // TODO Auto-generated method stub
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            responceLisnter.getResponceError(VollyError.TIMEOUT_ERROR, Tag);
                        } else if (error instanceof AuthFailureError) {
                            responceLisnter.getResponceError(VollyError.AUTH_ERROR, Tag);
                        } else if (error instanceof ServerError) {
                            responceLisnter.getResponceError(VollyError.SERVER_ERROR, Tag);
                        } else if (error instanceof NetworkError) {
                            responceLisnter.getResponceError(VollyError.NETWORK_ERROR, Tag);
                        }

                    }
                }) {

            /**
             * Passing some request headers
             * */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put(MyConstants.HeaderKey, HeaderKey);
                return headers;
            }


        };
        ;

        Applicationclass.getInstance().getRequestQueue().add(jsObjRequest);
        jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
}

在您的应用类

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;

import com.activeandroid.ActiveAndroid;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by ShashwatGupta on 08-08-2017.
 */

public class Applicationclass extends Application {
    private static Applicationclass mInstance;
    private RequestQueue mRequestQueue;
    public static Context context;

    public static synchronized Applicationclass getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

        mInstance = this;
        mRequestQueue = Volley.newRequestQueue(this);


    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }



    public RequestQueue getRequestQueue() {
        return mRequestQueue;
    }

}

从您的活动,致电方法

    ArrayList<RequestModel> list = new ArrayList<>();
       list.add(new RequestModel("Key", "Value"));
    list.add(new RequestModel("Key1", "Value1"));

    volleyJSonRequest.MakeJsonRequest(Tag, WEB_URL, list, responceLisnter, MyConstants.HeaderType);

创建响应侦听器的界面

    import org.json.JSONException;

public interface ResponceLisnter {

    void getResponce(String str, String Tag) throws JSONException;

    void getResponceError(String errorStr, String Tag);
}

您的请求MOdel

import org.json.JSONObject;

import java.util.ArrayList;

public class RequestModel {

    String Key;
    String Value;

    public ArrayList<JSONObject> getJsonObjects() {
        return jsonObjects;
    }

    public void setJsonObjects(ArrayList<JSONObject> jsonObjects) {
        this.jsonObjects = jsonObjects;
    }

    ArrayList<JSONObject> jsonObjects;

    public RequestModel(String key, String value) {
        this.Key = key;
        this.Value = value;
    }
    public RequestModel(String key, ArrayList<JSONObject> jsonObjects) {
        this.Key = key;
        this.jsonObjects = jsonObjects;
    }

    public String getValue() {
        return Value;
    }

    public void setValue(String value) {
        Value = value;
    }

    public String getKey() {
        return Key;
    }

    public void setKey(String key) {
        Key = key;
    }

}

和Header类型常量

public static final String HeaderType = "application/json; charset=utf-8";
public static final String HeaderKey = "Content-Type";