2016-11-11 16 views
0

我必須使用排球庫向網址發出POST請求。我已經建立了下面的自定義類凌空: - CustomJSONObjectRequestAndroid排除請求無法正常工作

import com.android.volley.AuthFailureError; 
import com.android.volley.Response; 
import com.android.volley.RetryPolicy; 
import com.android.volley.toolbox.JsonObjectRequest; 

import org.json.JSONObject; 

import java.util.HashMap; 
import java.util.Map; 

/** 
* Created by user on 4/14/2016. 
*/ 

public class CustomJSONObjectRequest extends JsonObjectRequest { 
    Map<String, String> mParams; 

    public CustomJSONObjectRequest(int method, String url, JSONObject jsonRequest, 
            Response.Listener<JSONObject> listener, 
            Response.ErrorListener errorListener) { 
     super(method, url, jsonRequest, listener, errorListener); 
    } 

    @Override 
    public Map<String, String> getHeaders() throws AuthFailureError { 
     HashMap<String, String> headers = new HashMap<String, String>(); 
     headers.put("Content-Type", "application/json; charset=utf-8"); 
     return headers; 
    } 

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

     return mParams; 
    } 

    @Override 
    public RetryPolicy getRetryPolicy() { 
     // here you can write a custom retry policy 

     return super.getRetryPolicy(); 
    } 


} 

CustomVolleyRequestQueue

import android.content.Context; 

import com.android.volley.Cache; 
import com.android.volley.Network; 
import com.android.volley.RequestQueue; 
import com.android.volley.toolbox.BasicNetwork; 
import com.android.volley.toolbox.DiskBasedCache; 
import com.android.volley.toolbox.HurlStack; 

/** 
* Created by Devastrix on 4/14/2016. 
*/ 
public class CustomVolleyRequestQueue { 

    private static CustomVolleyRequestQueue mInstance; 
    private static Context mCtx; 
    private RequestQueue mRequestQueue; 

    private CustomVolleyRequestQueue(Context context) { 
     mCtx = context; 
     mRequestQueue = getRequestQueue(); 
    } 

    public static synchronized CustomVolleyRequestQueue getInstance(Context context) { 
     if (mInstance == null) { 
      mInstance = new CustomVolleyRequestQueue(context); 
     } 
     return mInstance; 
    } 

    public RequestQueue getRequestQueue() { 
     if (mRequestQueue == null) { 
      Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024); 
      Network network = new BasicNetwork(new HurlStack()); 
      mRequestQueue = new RequestQueue(cache, network); 
      // Don't forget to start the volley request queue 
      mRequestQueue.start(); 
     } 
     return mRequestQueue; 
    } 

} 

我使用下面的函數使POST請求: -

RequestQueue mQueue = CustomVolleyRequestQueue.getInstance(context) 
       .getRequestQueue(); 
     String url = "someURL"; 
     Log.d("URL= ", url); 
     final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method.POST, url, 
       new JSONObject(), new Response.Listener<JSONObject>() { 

      @Override 
      public void onResponse(JSONObject response) { 

       Log.d("post: ", response+""); 

      } 

     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
        error.printStackTrace(); 


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

       Map<String,String> params = new HashMap<String, String>(); 
       params.put("A", "[[\"123\",\"456\",\"789\"]]"); // it is a json string actually 
       params.put("B", "23-11-2016"); 
       params.put("C", "ABC"); 
       return params; 
       //return query; 
      } 
     }; 
     jsonRequest.setTag(TAG); 
     int socketTimeout = TIMEOUT;//30 seconds - 
     RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); 
     jsonRequest.setRetryPolicy(policy); 
     mQueue.add(jsonRequest); 

但問題是請求正在返回空數據,而當我使用某些第三方應用程序進行POST請求時,它會返回正確的結果。什麼可能是可能的錯誤?

編輯 - 實際上,響應不爲空。真實的迴應是這樣的。

{ 
    "data" : "" 
} 

但數據的關鍵不應該有空洞value.SO我認爲這是與PARAMS或PARAMS沒有得到正確發送任何問題。但參數是完全正確的,我檢查過。

+0

您希望服務器響應成功的(2xx)POST而返回哪些數據?另外,該數據應該以何種格式存在? JSON? – clownba0t

+0

數據爲JSON格式。關鍵'數據'應該包含一些JSONObject,但是響應顯示'數據'鍵具有空鍵。 – devastrix

+0

我明白了。我能想到的唯一的事情是服務器真的沒有爲'data'屬性返回任何東西。嘗試在服務器端添加日誌記錄,以便您可以在構建響應時準確查看服務器打包到「數據」中的內容。或者,在應用程序方面,截取原始響應,然後將其中的數據轉換爲「JSONObject」,並檢查其內容。你應該可以通過覆蓋'protected Response parseNetworkResponse(NetworkResponse response){'並使用調試器或日誌記錄來做到這一點。 – clownba0t

回答

0

請將此依賴項添加到您項目的build.gradle方法中。 之後添加您想要發送到服務器的參數。

compile 'com.android.volley:volley:1.0.0' 

現在將此活動添加到您的項目中。

public class MainActivity extends AppCompatActivity { 
    private ProgressDialog progress_dialog; 
    private RequestQueue queue; 
    private HashMap<String, String> map = new HashMap<>(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     queue= Volley.newRequestQueue(getApplicationContext()); 
     GetEventCodeResponse("[email protected]","4"); 

    } 
    public void GetEventCodeResponse(String email,String event){ 
     progress_dialog = new ProgressDialog(this); 
     progress_dialog.setMessage("Getting data, please wait a moment..."); 
     progress_dialog.show(); 
     map.put("username", email); 
     map.put("eventcode", event); 
     getResponseFromServer("your own url",map); 
    } 
    public void getResponseFromServer(String url, final HashMap<String, String> map) { 
     System.out.println("url----"+url); 
     StringRequest stringRequest = new StringRequest(Request.Method.POST, url, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         Log.e("response reviw--",response); 
         progress_dialog.dismiss(); 
         /* rating();*/ 
        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         try{ 
          Log.e("sign error password", new String(error.networkResponse.data)); 

         }catch (Exception e){ 
          Toast.makeText(MainActivity.this, "try again", Toast.LENGTH_SHORT).show(); 
         } 

         progress_dialog.dismiss(); 
        } 
       }) 
     { 
      @Override 
      protected Map<String, String> getParams() { 
       return map; 
      } 
     }; 
     queue.add(stringRequest); 
     stringRequest.setRetryPolicy(new DefaultRetryPolicy(
       100000, 
       DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
       DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 
    } 
} 
+0

無法正常工作...此代碼實際上與我的工作相似 – devastrix

0

只是爲了確認,請求絕對是成功的和你提供的請求被稱爲與響應是nullResponse.Listener<JSONObject>實例的onResponse(JSONObject response)方法?

另外,是否有排球相關顯示在logcat?

更新響應意見

我的感覺是,我們還沒有鎖定了您遇到的問題一個明確的根源,所以我不能保證下面的代碼將解決它。但正如您所問,請嘗試以下操作:

RequestQueue mQueue = CustomVolleyRequestQueue.getInstance(context).getRequestQueue(); 
String url = "someURL"; 
Log.d("URL= ", url); 

final JSONObject requestBody; 
try { 
    requestBody = new JSONObject(); 
    requestBody.put("A", new JSONArray(new String[]{ "123", "456", "789" }); 
    requestBody.put("B", "23-11-2016"); 
    requestBody.put("C", "ABC"); 
} catch (JSONException exception) { 
    // error handling which, at least in theory, shouldn't be needed ... 
} 

final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method.POST, url, 
      requestBody, new Response.Listener<JSONObject>() { 

     @Override 
     public void onResponse(JSONObject response) { 

      Log.d("post: ", response+""); 

     } 

    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
       error.printStackTrace(); 


     } 
    }); 

jsonRequest.setTag(TAG); 
int socketTimeout = TIMEOUT;//30 seconds - 
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
     DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); 
jsonRequest.setRetryPolicy(policy); 
mQueue.add(jsonRequest); 
+0

是生成響應,但它爲空。不,我不使用Volley logcat – devastrix

+0

這很奇怪...'JsonObjectRequest'在成功時創建一個新的'JSONObject',如果它不能解析響應主體數據則拋出一個異常,所以我希望通過'onResponse'方法提供的'response'對象永遠不會爲'null '?對不起,我無法提供幫助......我會繼續考慮它! – clownba0t

+0

實際上,響應不爲空。真正的響應是將值作爲空字符串返回的鍵值對。所以我認爲這些參數有問題,或者參數沒有正確發送。但參數是完全正確的,我檢查過。 – devastrix