2013-08-02 11 views
6

Attualmente sto usando GsonRequest per emettere le richieste GET di riposo. Non chiaro su cosa utilizzare per le richieste PUT in cui devo inviare un oggetto JSon intero per essere aggiornato. L'oggetto Request accetta PUT ma non sono sicuro di come posizionare l'oggetto JSon che è previsto.come eseguire la richiesta PUT in Android Volley?

Ecco il mio JSON da mettere:

{ 
    prop1 : true, 
    prop2 : false, 
    prop4 : true 
} 

Ecco come la sua presentate in apiary.io ad esempio:

var xhr = new XMLHttpRequest(); 
    xhr.open('PUT', 'http://my.apiary.io/v1/records/{myid}.json'); 

    xhr.send("{\n \"isEditable\": false,\n \"isClosed\": true,\n  \"isAvail\": true\n}"); 

non so dove mettere il JSON.

Grazie

public class GsonRequest<T> extends Request<T> { 

private final Gson gson ; 
private final Class<T> clazz; 
private final Map<String, String> headers; 
private final Listener<T> listener; 

public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, 
     Listener<T> listener, ErrorListener errorListener) { 
    super(method, url, errorListener); 

    GsonBuilder gsonBuilder = new GsonBuilder(); 
    gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer()); 
    this.gson = gsonBuilder.create(); 
    this.clazz = clazz; 
    this.headers = headers; 
    this.listener = listener; 
} 

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    return headers != null ? headers : super.getHeaders(); 
} 

@Override 
protected void deliverResponse(T response) { 
    listener.onResponse(response); 
} 

@Override 
protected Response<T> parseNetworkResponse(NetworkResponse response) { 
    try { 
     String json = new String(
       response.data, HttpHeaderParser.parseCharset(response.headers)); 
     return Response.success(
       gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response)); 
    } catch (UnsupportedEncodingException e) { 
     return Response.error(new ParseError(e)); 
    } catch (JsonSyntaxException e) { 
     return Response.error(new ParseError(e)); 
    } 
    } 
} 

E qui sono i metodi di base getBody all'interno della richiesta. Sembra gestire i parametri sul Method.PUT, ma cosa succede se è una stringa JSON che deve essere inviata nel corpo?

/** 
* Returns the raw POST or PUT body to be sent. 
* 
* @throws AuthFailureError in the event of auth failure 
*/ 
public byte[] getBody() throws AuthFailureError { 
    Map<String, String> params = getParams(); 
    if (params != null && params.size() > 0) { 
     return encodeParameters(params, getParamsEncoding()); 
    } 
    return null; 
} 

/** 
* Converts <code>params</code> into an application/x-www-form-urlencoded encoded string. 
*/ 
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) { 
    StringBuilder encodedParams = new StringBuilder(); 
    try { 
     for (Map.Entry<String, String> entry : params.entrySet()) { 
      encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding)); 
      encodedParams.append('='); 
      encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding)); 
      encodedParams.append('&'); 
     } 
     return encodedParams.toString().getBytes(paramsEncoding); 
    } catch (UnsupportedEncodingException uee) { 
     throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee); 
    } 
} 

soluzione consigliata:

 // add a Json body. 
    public String jsonBody; 

    /** 
    * Returns the raw POST or PUT body to be sent. 
    * 
    * @throws AuthFailureError in the event of auth failure 
    */ 



    public byte[] getBody() throws AuthFailureError { 

    if ((getMethod() == Method.PUT) && (jsonBody != null)) 
    { 
     return jsonBody.getBytes(); // Encoding required????? 

    } 
    else 
    { 
     return super.getBody(); 
    } 

} 

risposta

5

La classe base astratta Request ha un costruttore che prende un Request.Method come primo parametro. Tutte le implementazioni di richiesta in volley.toolbox hanno anche un costruttore come quello.

non sono sicuro dove GsonRequest proviene da ma se non dispone di un costruttore che prende un Method, è possibile aggiungere uno voi stessi.

Modifica: è possibile ignorare getBody e getBodyContentType per restituire rispettivamente il corpo della richiesta personalizzata e il tipo MIME.

+0

Ho aggiornato la mia domanda con GsonRequest. Non so dove mettere la stringa JSON in questa richiesta. – TestBest

+4

Sembra che non supporti l'invio di dati. Dovresti sovrascrivere 'getBody' e' getBodyContentType' per restituire l'oggetto serializzato e un tipo MIME appropriato (ad es. 'Application/json') – Delyan

+0

Ho postato come put viene invocato in javascript apiary.io – TestBest

Problemi correlati