2015-09-04 37 views
-1

我可以接收一個json數組,但是如何使用volley發送一個json數組?我怎樣才能發送一個json數組到webserver使用凌空?

JsonArrayRequest arrayReq = new JsonArrayRequest(URL, 
     new Listener<JSONArray>() { 

} 
+0

你能給更多信息或更多的代碼?你在管理Web服務嗎?您的Web服務器必須實現一些POST/PUT請求來獲取這些值,然後執行任何你想要的。有時你需要授權才能創建並給出一些值對(鍵和值) –

+0

我認爲創建JsonArray的簡單方法是使用JSONArray。 (import org.json.JSONArray),並簡單地使用volley在POST中發送一個String參數。 –

回答

0

嘗試使用下面的代碼段實現它,我希望它會工作:

public class JsonPostArrayRequest extends JsonRequest<JSONObject> { 

    JSONArray params; 
    public JsonPostArrayRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener,JSONArray params) { 
     super(Method.POST, url, null, listener, errorListener); 
     this.params=params; 
    } 

    @Override 
    public byte[] getBody() { 
      if (this.params != null && this.params.length() > 0) { 
       return encodeParameters(this.params, getParamsEncoding()); 
      } 
      return null; 

     } 

    private byte[] encodeParameters(JSONArray params, String paramsEncoding) { 
      try { 
       return params.toString().getBytes(paramsEncoding); 
      } catch (UnsupportedEncodingException uee) { 
       throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee); 
      } 
     } 

     @Override 
     protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { 
      try { 
       String jsonString = 
         new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 
       return Response.success(new JSONObject(jsonString), 
         HttpHeaderParser.parseCacheHeaders(response)); 
      } catch (UnsupportedEncodingException e) { 
       return Response.error(new ParseError(e)); 
      } catch (JSONException je) { 
       return Response.error(new ParseError(je)); 
      } 
     } 
} 
相關問題