volley的使用

首相要创建项目加上依赖compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28'

定义自己的app

package alice.bw.com.day12volley;

import android.app.Application;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * @author alice
 * @version 1.0
 * @Date 2017/10/12 20:33
 */
public class MyApp extends Application {
    // 只能有一个    静态  单例 等等 请求队列
    private static RequestQueue requestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
        //  初始化一个 请求队列   Volley  建议 每个 app 只有一个  请求队列
        requestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    public static RequestQueue getRequestQueue() {
        return requestQueue;
    }
}
在我们的清单文件中使用自定义的app

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="alice.bw.com.day12volley">
    <uses-permission android:name="android.permission.INTERNET"/>


    <application
        android:allowBackup="true"
        android:name=".MyApp"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


在我们的主布局中

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="alice.bw.com.day12volley.MainActivity">

    <Button
        android:id="@+id/get_bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Get网络请求" />

    <Button
        android:id="@+id/post_bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Post网络请求" />

    <Button
        android:id="@+id/object_bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Object网络请求" />

    <Button
        android:id="@+id/array_bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Array网络请求" />

    <ImageView
        android:id="@+id/show_iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>



在我们的主Activity中

package alice.bw.com.day12volley;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        switch (view.getId()){
            case R.id.get_bt:
            String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
              /*
                   第一个参数  : 请求方式  GET  POST
                   第二个参数 :  请求的   url
                   第三个参数:   请求成功的   监听器
                   第四个参数     请求失败的监听器

               */
            final StringRequest request = new StringRequest(Request.Method.GET, String.format(path, 1), new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("sxl", "onResponse: " + response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("sxl", "onErrorResponse: " + error);
                }
            });

            StringRequest request2 = new StringRequest(Request.Method.GET, String.format(path, 1), new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("sxl", "onResponse2: " + response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("sxl", "onErrorResponse2: " + error);
                }
            });
            // 添加Tag 作为标记  可以根据该标记将这个请求取消掉
            request2.setTag("cancel");
            request.setTag("cancel");


            //  将此次请求添加到 请求队列中   多个请求添加到 队列中会按照顺序执行
            MyApp.getRequestQueue().add(request2);
            MyApp.getRequestQueue().add(request);
            break;
            case R.id.post_bt:


                //post提交的字段:pageNo=1&pageSize=20&serialIds=2143,3404&v=4.0.0
                String pathPost = "http://mrobot.pcauto.com.cn/v2/cms/channels/1?";

                StringRequest postRequest = new StringRequest(Request.Method.POST, pathPost, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("sxl", "onResponse——post: " + response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("sxl", "onErrorResponse: ");
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        //                        pageNo=1&pageSize=20&serialIds=2143,3404&v=4.0.0

                        //                         该方法用来拼字段表单
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("pageNo", "1");
                        map.put("pageSize", "20");
                        map.put("serialIds", "2143,3404");
                        map.put("v", "4.0.0");
                        return map;
                    }
                };

                // 所有请求 都必须添加到队列中才执行
                MyApp.getRequestQueue().add(postRequest);
                break;

            case R.id.object_bt:
                String object_path = "http://mrobot.pcauto.com.cn/v2/cms/channels/1?pageNo=1&pageSize=20&serialIds=2143,3404&v=4.0.0";
                JsonObjectRequest objectRequest = new JsonObjectRequest(object_path, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        Log.d("sxl", "onResponseObjevt: " + response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("sxl", "onErrorResponse: ");
                    }
                });
                MyApp.getRequestQueue().add(objectRequest);
                break;
            case R.id.array_bt:
                //                JsonArrayRequest  arrayRequest =  new JsonArrayRequest()
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消标记为  cancel 的 请求
        MyApp.getRequestQueue().cancelAll("cancel");
    }


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值