2015-11-01 66 views
1

我使用的是android volley,我想用stringRequest發送發佈數據。 但參數不發送到服務器。這裏是我的代碼:Android StringRequest Volley不發送帖子值

 StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 

      @Override 
      public void onResponse(String response) { 

       Log.d(TAG, response); 


    } 
     }, new Response.ErrorListener() { 

      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.e(TAG, "Volley Error: " + error.getMessage()); 


      } 

     }) 
    { 

      @Override 
      protected Map<String, String> getParams() { 

       params = new HashMap<String, String>(); 
       params.put("tag", "openApp"); 
       Log.d("Params", params + ""); 

       return params; 
      } 
     }; 

    jsonObjReq.setShouldCache(false); 


     AppController.getInstance().addToRequestQueue(jsonObjReq); 

我不知道什麼是錯的?

+0

您是否在RequestQueue中添加了抽籤請求? – bond007

+0

是的,我添加了,我更新了代碼, –

+0

首先嚐試檢查發佈請求是否通過其他基於瀏覽器的插件發送,如休息簡單。 – bond007

回答

0

是的錯誤是關於服務器和我的代碼是正確的。

2

而不是getParams,您應該使用getBody爲您的POST請求。

您可以參考我的以下工作示例代碼(將我的JSONObject和Url替換爲您的)。希望這可以幫助!

 ... 
     try { 
      RequestQueue queue = Volley.newRequestQueue(this); 
      jsonBody = new JSONObject(); 
      jsonBody.put("Title", "Android Volley POST DATA Demo"); 
      jsonBody.put("Author", "BNK"); 
      jsonBody.put("Date", "2015/11/01"); 
      requestBody = jsonBody.toString(); 

      StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        // do something... 
       } 
      }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        // do something... 
       } 
      }) { 
       @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) { 
         e.printStackTrace(); 
         return null; 
        } 
       } 
      }; 
      queue.addToRequestQueue(stringRequest); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     ... 
+0

無法使用。我上週使用了getParams()並正常工作,但突然崩潰了。 –

+0

Suddendly墜毀?任何logcat可用? – BNK

+0

此代碼不工作,getParams上週工作,但現在不工作。並且沒有參數發送到服務器。 D/Response:{「error」:true,「error_msg」:「必需參數'tag'丟失!」} –