-
首先呢肯定是导入依赖:
compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
-
导入依赖之后呢:
//首先得到一个RequestQueue 顾名思义也就是请求队列 RequestQueue queue = Volley.newRequestQueue(this); //然后创建请求 StringRequest request = new StringRequest("http://www.baidu.com", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("MainActivity这就是咱们得到的值", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); //给请求队列添加请求 queue.add(request);
这只是一个简单的网络请求Volley成的好处就是直接把返回的数据转换成String类型的有人就问了只能转换成String? 才不是呢!接着往下看:
ImageRequest request1 = new ImageRequest("你图片的url", new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
imageView.setImageBitmap(response);
}
}, 100, 100, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {} }); queue.add(request1);
有人也许就说了这么多的构造参数我哪知道什么意思!
别急我慢慢给你讲:
1.第一个是你图片的url
2.第二个是你请求成功的回调
3.第三个是图片规定最大的宽度
4.第四个是你要使用哪种位图格式来解码
5.第五个就是请求失败的回调
- 当然你也可以自定义Request,这里就贴一个j简单的 GsonRequest的代码:
public class GsonRequest extends Request<Object> {
private final Response.Listener<Object> mListener;
Object ob;
public GsonRequest(int method, String url, Response.Listener<Object> listener,
Response.ErrorListener errorListener,Object ob) {
super(method, url, errorListener);
mListener = listener;
this.ob = ob;
}
public GsonRequest(String url, Response.Listener<Object> listener, Response.ErrorListener errorListener,Object ob) {
this(Method.GET, url, listener, errorListener,ob);
}
@Override
protected void deliverResponse(Object response) {
mListener.onResponse(response);
}
@Override
protected Response<Object> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
Gson g = new Gson();
Object obj = (Object) g.fromJson(parsed,ob.getClass());
return Response.success(obj, HttpHeaderParser.parseCacheHeaders(response));
}
}
记得加上网络权限 :
<uses-permission android:name="android.permission.INTERNET" />
基本用法就这样了。sky