1.导包
2.自己写个类继承Application
public class myapp extends Application {
private static RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate();
requestQueue= Volley.newRequestQueue(getApplicationContext());
}
public static RequestQueue getRequestQueue(){
return requestQueue;
}
}
3.在AndroidManifest中使用
4.主函数
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void cc(View view) {
switch (view.getId()){
case R.id.but1:
get();
break;
case R.id.but2:
post();
break;
}
}
private void post() {
String str= "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
StringRequest sr=new StringRequest(Request.Method.POST, str, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap map=new HashMap();
map.put("pageNo", "1");
map.put("pageSize", "20");
map.put("serialIds", "2143,3404");
map.put("v", "4.0.0");
return map;
}
};
sr.setTag("call");
myapp.getRequestQueue().add(sr);
}
public void get() {
String str= "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
StringRequest sr=new StringRequest(Request.Method.GET,str, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("aaaa", "onResponse: "+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("aaaa", "onErrorResponse: "+error.toString());
}
});
sr.setTag("ace");
myapp.getRequestQueue().add(sr);
}
@Override
protected void onDestroy() {
super.onDestroy();
myapp.getRequestQueue().cancelAll("ace");
myapp.getRequestQueue().cancelAll("call");
}
}
5.主布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/but1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get请求"
android:onClick="cc"/>
<Button
android:id="@+id/but2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post请求"
android:onClick="cc"/>
</LinearLayout>