Android排除请求无法正常工作

问题描述:

我必须使用排球库向网址发出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

请将此依赖项添加到您项目的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

只是为了确认,请求绝对是成功的和你提供的请求被称为与响应是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