2016-02-24 56 views
0

我必須使用以下參數進行json發佈請求。排除返回錯誤響應

{"method":"login","data":{"username":"korea","password":"123456"}} 

我使用凌空作出發佈請求和follwoing是我的代碼做post請求。

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, loginURL, null, 
         new Response.Listener<JSONObject>() { 
          @Override 
          public void onResponse(JSONObject response) { 
           Toast.makeText(mContext,response.toString(),Toast.LENGTH_SHORT).show(); 

          } 
         }, 
         new Response.ErrorListener() { 
          @Override 
          public void onErrorResponse(VolleyError error) { 
           Log.e("Volley", "Error"); 

          } 
         } 
       ){ 
        @Override 
        protected Map<String, String> getParams() throws AuthFailureError { 
         Map<String,String> map = new HashMap<String,String>(); 
         map.put("method","login"); 
         map.put("username","korea"); 
         map.put("password","123456"); 
         return map; 
        } 
       }; 
       requestQueue.add(jsonObjectRequest); 
       requestQueue.start(); 

我得到服務器的錯誤響應。如何從服務器獲得適當的響應?

+1

什麼錯誤響應的服務器給你? –

回答

1

Request.Method.GET更改爲Request.Method.POST。然後傳遞一個JSONObject作爲第三個參數,你現在有null;

例如:

JSONObject data = new JSONObject(); 
data.put("username","korea"); 
data.put("password","123456"); 

JSONObject jsonObject = new JSONObject(); 
jsonObject.put("method","login"); 
jsonObject.put("data",data); 

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, loginURL, jsonObject, responseListener, errorListener); 
+0

我得到'com.android.volley.ParseError:org.json.JSONException:在字符0輸入結束' –

+0

我認爲這意味着服務器發送一個空的響應。您可以使用Chrome的Advanced Rest Client附加軟件對其進行測試。 – Nfear

+0

它像一個魅力。謝謝 –

1

I use volley to make post request and follwoing is my code to do post request

這不是POST請求,AFAICT。您正在使用Request.Method.GET

1

使用下面的方法把數據上傳到服務器

public void postDataVolley(Context context,String url,JSONObject sendObj){ 
    try { 
     RequestQueue queue = Volley.newRequestQueue(context); 

     JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       Log.d("Volley", "Volley JSON post" + response); 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Log.d("Volley", "Volley JSON post" + "That didn't work!"); 
      } 
     }); 

     queue.add(jsonObj); 

    }catch(Exception e){ 

    } 
} 
+0

它會引發以下錯誤'com.android.volley.ParseError:org.json.JSONException:字符0處的輸入結束' –