一口一口吃掉Volley(二)

JerryXia 发表于 , 阅读 (0)

相信看了第一篇教程之后,你应该会对Volley有一个初步的了解了吧,那接下来就继续学习如何使用Volley进行开发吧!

配置Gradle

使用如下命令导入Volley库:

1
compile 'com.mcxiaoke.volley:library:1.0.19'
  • 如果你还是使用Eclipse进行开发的话,可以下载volley的jar包导入工程。

添加联网许可

在AndroidManifest.xml文件中添加联网的请求

1
<uses-permission android:name="android.permission.INTERNET"/>

使用StringRequest

如果你需要通过网络访问的资源属于String字符串的资源,那么使用StringRequest就最为简单了,只需按照如下步骤就行了。

① 获取一个RequestQueue

1
RequestQueue mQueue = Volley.newRequestQueue(this);

② 构造一个StringRequest对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
StringRequest stringRequest=new StringRequest("http://www.wensibo.top"
, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//正常情况下的逻辑处理
String result="";
try {
result= new String(response.getBytes("ISO_8859_1"), "utf-8");
//由于访问string的时候可能会出现乱码情况,所以保险起见,可以将其转换为utf-8格式
//对于其他的自定义Requet都是同理的,均需要在重写parseNetworkResponse方法时设置编码格式,避免乱码的出现
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Intent intent = new Intent();
intent.setClass(MainActivity.this, StringRequestActivity.class);
intent.putExtra("string_request", result);
startActivity(intent);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//出错的时候做的一些处理
Intent intent = new Intent();
intent.setClass(MainActivity.this, StringRequestActivity.class);
intent.putExtra("string_request", getResources().getString(R.string.error_message));
startActivity(intent);
}
}
);

由于不同的网页的编码格式不同,为了防止中文乱码情况的出现,代码中将其设置为utf-8即可得到解决。其他的Request如果要避免乱码的出现,也应该采取类似的方法进行处理。

③ 将StringRequest对象add进RequestQueue

1
mQueue.add(stringRequest);

看看截图