Volley
一个 2013 年谷歌 IO 大会发布的访问网络的框架。话说今年的 IO 大会也准备要开启了,十万个期待啊。
由于这个框架十分好用 (也应用了在我的毕设),所以作个简单笔记。
HttpURLConnection 和 HttpClient
在之前,我们访问网络,通常都是使用HttpURLConnection和HttpClient,它们的用法比使用框架要复杂一点。
不过,要是不使用框架与网络通信的话,这两个我们又该如何选择呢?
见 :
http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Volley 的优点:
- 字符串、json 数据、图片的异步加载
- 基于队列的网络请求
- 网络请求的优先级
- 请求缓存机制
- 使用简单,适合频繁的网络访问
- Custom views 加载图片(
Custom views等)
Volley 的使用
在这里不再写重复的东西了,参考下面两位兄弟的文章。
第一篇主要讲 volley 的特点,怎么使用,更深一点的使用(发送 post 请求、使用 cookies、设置请求 Headers 等等)。
第二篇和第三篇主要详细讲述 volley 的使用。
Asynchronous HTTP Requests in Android Using Volley
主要遇到的问题
1、出现中文乱码
解决。参考
我的代码:
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 | public class JsonArrayUTF8Request extends JsonArrayRequest { public JsonArrayUTF8Request(String url, Listener<JSONArray> listener, ErrorListener errorListener) { super(url, listener, errorListener); // TODO Auto-generated constructor stub } @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String type = response.headers.get(HTTP.CONTENT_TYPE); if (type == null) { type = "charset=UTF-8"; response.headers.put(HTTP.CONTENT_TYPE, type); } else if (!type.contains("UTF-8")) { type += ";" + "charset=UTF-8"; response.headers.put(HTTP.CONTENT_TYPE, type); } } catch (Exception e) { // print stacktrace e.g. } return super.parseNetworkResponse(response); } } |
2、发送 post 请求
在这篇文章有说明
我的代码:
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 30 | private void takeLogin() {
String url = Common.LOGIN;
JSONObject infoObject = new JSONObject();
try {
infoObject.put("userName", username.getText().toString());
infoObject.put("password", password.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, infoObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
responseDo(jsonObject);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
rQueue.add(jsonObjectRequest);
rQueue.start();
}
|