Volley的中文翻译为“齐射、并发”,是在2013年的Google大会上发布的一款Android平台网络通信库,具有网络请求的处理、小图片的异步加载和缓存等功能,能够帮助 Android APP 更方便地执行网络操作,而且更快速高效。
适用场景:
Volley:数据量小,网络通信频繁的操作,即时通信、社交等应用;
XUtils:大文件上传与下载等以及各种工具类的使用,电商、社区等应用。
不同场景不同工具。
话不多说,开始项目,因为我们网络请求需要访问API,因此在这里我们先介绍:
百度的APIStore:
http://apistore.baidu.com/
为开发者提供最全面的API服务。
在这里我们用到天气预报_易源。(http://apistore.baidu.com/apiworks/servicedetail/515.html)
接口地址 :http://apis.baidu.com/showapi_open_bus/weather_showapi/areaid
请求方法 :GET
参数名 | 类型 | 必填 | 参数位置 | 描述 | 默认值 |
---|---|---|---|---|---|
string | 是 | header |
参数名 | 类型 | 必填 | 参数位置 | 描述 | 默认值 |
---|---|---|---|---|---|
string | 是 | urlParam |
开始Coding,先写一个布局文件,这里写一个TextView用于显示请求API后返回的数据:
compile 'com.mcxiaoke.volley:library:1.0.+'
然后同步一下,就可以加载Volley框架了。
准备工作搞定,下面开始核心源代码:
1.准备控件和自己的APIKey(注册账号,申请十分方便):
private TextView message_tv_main;
public static String API_KEY = "xxx";
message_tv_main = (TextView) findViewById(R.id.message_tv_main);
RequestQueue requestQueue = Volley.newRequestQueue(this);
String urlJsonObjectRequest = "http://apis.baidu.com/showapi_open_bus/weather_showapi/areaid?area=%E5%8C%97%E4%BA%AC";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonObjectRequest, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
message_tv_main.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
message_tv_main.setText(error.getMessage());
}
}) {
@Override
public Map getHeaders() throws AuthFailureError {
HashMap hashMap = new HashMap<>();
hashMap.put("apikey", API_KEY);
return hashMap;
}
};
requestQueue.add(jsonObjectRequest);
StringRequest使用方法类似:
String url = "http://apis.baidu.com/apistore/idservice/id";
String param = "id=420984198704207896";
String urlParam = url + "?" + param;
StringRequest stringRequest = new StringRequest(urlParam, new Response.Listener() {
@Override
public void onResponse(String response) {
message_tv_main.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
message_tv_main.setText(error.getMessage());
}
}){
@Override
public Map getHeaders() throws AuthFailureError {
HashMap hashMap = new HashMap<>();
hashMap.put("apikey",API_KEY);
return hashMap;
}
};