2017-10-09 61 views
0

我是Android新手。我正在弄清楚如何進行網絡通話。我正在嘗試發送標題以及JSON數據。我試過調試代碼,但它不會去onResponse()。有人能告訴我我做錯了什麼。排球請求不給予任何迴應

以下是我的代碼。

String url = "https://api....."; 
    RequestQueue requestQueue = Volley.newRequestQueue(this); 
    JSONObject jsonObject = new JSONObject(); 
    try { 
     jsonObject.put("image", "https://i.imgur.com/5KdM.jpg"); 
     jsonObject.put("subject_id", "Elixabeth"); 
     jsonObject.put("gallery_name", "MyGallery"); 
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 

       if (response != null){ 

       } 
       // do something... 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       // do something... 
      } 
     }) { 
      @Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       final Map<String, String> headers = new HashMap<>(); 
       headers.put("Content-Type", "application/json"); 
       headers.put("app_id", ""); 
       headers.put("app_key", ""); 
       headers.put("Content-Length", "124"); 

       return headers; 
      } 
     }; 
     requestQueue.add(jsonObjectRequest); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

我在Postman中試了同樣的數據,我得到的迴應。

+0

你是否嘗試登錄onErrorResponse方法?你有一些stackTrace日誌? – tebitoq

+0

你有沒有找到onErrorResponse()? –

+0

我解決了它,但它有點奇怪。內容長度是api期待的問題96.但是我發送了124.但是,124這是郵遞員的工作。有人可以解釋原因嗎? – Stackover67

回答

0

將日誌放入 onResponse(JSONObject響應)方法 Log.d(「Response」,response.toString()); (VolleyError error)方法 Log.e(「Error」,error.getMessage());和 onErrorResponse(VolleyError error)。 然後檢查logcat,你可以找到出了什麼問題......

+0

解決了它。但它有點奇怪。內容長度是問題。該api期待96 ..但我發送124.但與124它是在郵遞員工作。有人可以解釋原因嗎? – Stackover67

+0

可能會將JsonObjectRequest更改爲StringRequest將解決您的問題.. –