如何使用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();
}
答案 0 :(得分:1)
您可以像这样设置GET排球请求
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;
}
答案 1 :(得分:0)
以下是我使用Volley
获取字符串响应的完整方法。如果传递参数,请使用POST方法。定义您的价值并发布网址。使用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();
}
});
}