您的位置:首页 > 理论基础 > 计算机网络

Android网络通信必备神器Volley详解——发送一个标准的Request

2015-11-12 14:48 751 查看
Volley主要支持一下几种Request

1. StringRequest:确定一个URL,获得返回的原始字符串。

2. ImageRequest:确定一个URL,获得一个图片。

3. JsonObjectRequest和JsonArrayRequest: 确定一个URL,获得JSON对象或者数字。

请求一个图片

使用ImageRequest

<span style="font-size:14px;">ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
<strong> public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}</strong>
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);</span>


使用ImageLoader和NetworkImageView

使用ImageLoader 和NetworkImageView来有效的加载多张图片,比如在ListView中加载图片。

在你layout的XML文件中
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="150dp"
android:layout_height="170dp"
android:layout_centerHorizontal="true" />


加载图片
ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private static final String IMAGE_URL =
"http://developer.android.com/images/training/system-ui.png";
...

// Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

// Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();

// Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);


正如上篇文章里说的,把RequestQueue封装起来使得图片的cache独立于Activity,当屏幕进行旋转的时候图片不用重新从网络下载,不会造成闪屏。

请求JSON

与前面的Request类似,直接看代码
TextView mTxtDisplay;
ImageView mImageView;
mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://my-json-feed";

JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
mTxtDisplay.setText("Response: " + response.toString());
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub

}
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息