如何使用Volley
GET方法传递参数?
private void getData(int ClassIDs){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "";
StringRequest request = new StringRequest(com.android.volley.Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(ActivityStarsEntryTestPrep.this, "Success", Toast.LENGTH_SHORT).show();
}
发布于 2018-05-31 17:15:43
您可以这样设置GET volley request
StringRequest commonRequest = new StringRequest(Request.Method.GET, url/* URL OF WEBSERVICE*/, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//HANDLE RESPONSE
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No
// connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user
// credentials.
// For ClientError, 400 & 401, Errors happening on
// client side when sending api request.
// In this case you can check how client is forming the
// api and debug accordingly.
// For ServerError 5xx, you can do retry or handle
// accordingly.
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("KEY","VALUE");
return hashMap;
}
};
commonRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 2));
INSTANCE OF VOLLEY.addToRequestQueue(commonRequest);
这部分代码对您很有用
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("KEY","VALUE");
return hashMap;
}
发布于 2018-05-31 17:29:29
下面是我使用Volley
获取字符串响应的完整方法。如果传递参数,请使用POST方法。定义您的值和发布URL。使用onResponse
方法获取响应。
public void getPostData() {
String value = "value";
String s; //to get response
final String URL = "Your php URL paste here";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
s = response;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityName.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("value", value.toString);
return hashMap;
}
};
final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
@Override
public void onRequestFinished(Request<Object> request) {
requestQueue.getCache().clear();
}
});
}
https://stackoverflow.com/questions/50620511
复制相似问题