首先我们在项目中导入这个框架:
implementation 'com.mcxiaoke.volley:library:1.0.19'
在AndroidManifest文件当中添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
下面是我们的首页布局:
在这个布局当中我们将Volley框架的所有功能都做成了一个按钮,按下按钮之后就会在“显示结果”下面显示结果,显示结果下面使用了一个ScrollView,并在ScrollView下面嵌套了一个Textview和Imageview,用于把我们加载成功之后的图片和文字进行显示。
下面是首页布局的代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get请求"/> <Button android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Post请求"/> <Button android:id="@+id/json" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="请求JSON"/> <Button android:id="@+id/ImageRquest" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ImageRquest加载图片"/> <Button android:id="@+id/ImageLoader" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ImageLoader加载图片"/> <Button android:id="@+id/NetWorkImageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="NetWorkImageView加载图片"/> <TextView android:text="显示结果" android:textSize="20sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:visibility="gone" android:id="@+id/iv_volley" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <com.android.volley.toolbox.NetworkImageView android:id="@+id/NetWork" android:visibility="gone" android:layout_width="200dp" android:layout_height="200dp" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_volley_result" android:layout_width="match_parent" android:layout_height="match_parent" /> </ScrollView> </LinearLayout>
为了实现Get请求,进行Get请求一共需要三步,分别是:
-
创建一个请求队列
-
创建一个请求
-
将创建的请求添加到请求队列当中
在创建请求的时候,必须同时写两个监听器,一个是实现请求,正确接受数据的回调,另一个是发生异常之后的回调。这里我们准备了json数据,是在gank.io的官网上找的,大家可以自行百度一下,这里就直接采用了网址:
http