2015-11-06 14 views
18

Sto sviluppando un'applicazione Android che comunica con un servizio web RESTful che ho scritto. L'utilizzo di Volley per i metodi GET è fantastico e facile, ma non riesco a mettere il dito sui metodi POST.Come inviare una richiesta POST usando il volley con il corpo della stringa?

voglio inviare una richiesta POST con un String nel corpo della richiesta, e recuperare la risposta grezza del servizio web (come 200 ok, 500 server error).

Tutto quello che ho trovato è il StringRequest che non consente di inviare con i dati (corpo), e inoltre mi limita a ricevere una risposta analizzata String. Mi sono imbattuto anche in JsonObjectRequest che accetta dati (corpo) ma recuperiamo una risposta analizzata JSONObject.

Ho deciso di scrivere la mia implementazione, ma non riesco a trovare un modo per ricevere la risposta non elaborata dal servizio web. Come posso farlo?

risposta

58

È possibile fare riferimento al seguente codice (naturalmente è possibile personalizzare per avere maggiori dettagli della risposta della rete):

try { 
    RequestQueue requestQueue = Volley.newRequestQueue(this); 
    String URL = "http://..."; 
    JSONObject jsonBody = new JSONObject(); 
    jsonBody.put("Title", "Android Volley Demo"); 
    jsonBody.put("Author", "BNK"); 
    final String requestBody = jsonBody.toString(); 

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      Log.i("VOLLEY", response); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.e("VOLLEY", error.toString()); 
     } 
    }) { 
     @Override 
     public String getBodyContentType() { 
      return "application/json; charset=utf-8"; 
     } 

     @Override 
     public byte[] getBody() throws AuthFailureError { 
      try { 
       return requestBody == null ? null : requestBody.getBytes("utf-8"); 
      } catch (UnsupportedEncodingException uee) { 
       VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8"); 
       return null; 
      } 
     } 

     @Override 
     protected Response<String> parseNetworkResponse(NetworkResponse response) { 
      String responseString = ""; 
      if (response != null) { 
       responseString = String.valueOf(response.statusCode); 
       // can get more details such as response.headers 
      } 
      return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response)); 
     } 
    }; 

    requestQueue.add(stringRequest); 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
+1

uomo freddo ... si salva la mia giornata :) –

+1

Ha funzionato benissimo per me. Quota impressionante! –

+1

Il suo operato, ma ha dovuto rimuovere bodyContentType e parseNetworkResponse metodi – kondal

7

mi piaceva this uno, ma è sending JSON not string come richiesto nella domanda, reinserire il codice qui, nel caso in cui il github originale sia stato rimosso o modificato, e questo trovato utile per qualcuno.

public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){ 
    mPostCommentResponse.requestStarted(); 
    RequestQueue queue = Volley.newRequestQueue(context); 
    StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      mPostCommentResponse.requestCompleted(); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      mPostCommentResponse.requestEndedWithError(error); 
     } 
    }){ 
     @Override 
     protected Map<String,String> getParams(){ 
      Map<String,String> params = new HashMap<String, String>(); 
      params.put("user",userAccount.getUsername()); 
      params.put("pass",userAccount.getPassword()); 
      params.put("comment", Uri.encode(comment)); 
      params.put("comment_post_ID",String.valueOf(postId)); 
      params.put("blogId",String.valueOf(blogId)); 

      return params; 
     } 

     @Override 
     public Map<String, String> getHeaders() throws AuthFailureError { 
      Map<String,String> params = new HashMap<String, String>(); 
      params.put("Content-Type","application/x-www-form-urlencoded"); 
      return params; 
     } 
    }; 
    queue.add(sr); 
} 

public interface PostCommentResponseListener { 
    public void requestStarted(); 
    public void requestCompleted(); 
    public void requestEndedWithError(VolleyError error); 
}