Volley经常用于频繁请求数据量不大的时候,用法:
public class MyApplication extends Application {
public static RequestQueue queue;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
queue = Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getHttpQueue() {
return queue;
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//volley_Get();
volley_Post();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
MyApplication.getHttpQueue().cancelAll("abcPost");//通过之前设置的TAG取消
MyApplication.getHttpQueue().cancelAll("abcGet");
}
private void volley_Post() {
String url = "http://apis.juhe.cn/mobile/get?";
StringRequest request = new StringRequest(Method.POST, url,
new Listener<String>() {
@Override
public void onResponse(String arg0) {
Toast.makeText(MainActivity.this, arg0,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
Toast.makeText(MainActivity.this, "网络请求失败",
Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
map.put("phone", "13666666666");
map.put("key", "335adcc4e891ba4e4be6d7534fd54c5d");
return map;
}
};
request.setTag("abcPost");
MyApplication.getHttpQueue().add(request);
}
private void volley_Get() {
String url = "http://apis.juhe.cn/mobile/get?phone=15821591618&key=335adcc4e891ba4e4be6d7534fd54c5d";
StringRequest request = new StringRequest(Method.GET, url,
new Listener<String>() {
@Override
public void onResponse(String arg0) {
Toast.makeText(MainActivity.this, arg0,
Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
Toast.makeText(MainActivity.this, "网络请求失败",
Toast.LENGTH_LONG).show();
}
});
request.setTag("abcGet");
MyApplication.getHttpQueue().add(request);
}
}