[英]How to send json format data to volley using post method
我有一個使用排球集成的應用程序。 現在,我正在進行維護,因為我想將數據作為帶有逗號分隔值(例如{“ 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錯誤。 對不起這個基本問題。 我對齊射並不十分了解。請幫助我。
提前致謝。
只需創建一個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);
}
您的要求
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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.