[Android通信]Volley(一):String、Json和Image请求

参考链接:

http://blog.csdn.net/guolin_blog/article/details/17482095


0.

下载volley的jar包,并导入

下载地址:http://pan.baidu.com/s/1c0HiMnY


1.建立全局的请求队列

package com.example.testvolley;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import android.app.Application;

public class MyApplication extends Application {
	
	private static RequestQueue requestQueue;
	public static RequestQueue getRequestQueue() {
		return requestQueue;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		requestQueue = Volley.newRequestQueue(getApplicationContext());
	}
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testvolley"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name="com.example.testvolley.MyApplication" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2.

package com.example.testvolley;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private ImageView imageView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView);
		
//		stringGet();
//		stringPost();
//		jsonGet();
//		jsonPost();
//		imageRequest();
//		imageLoader();
//		networkImageView();
	}

	private void stringGet() 
	{
		String url = "http://www.baidu.com";
		StringRequest sr = new StringRequest(Method.GET, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				Log.v("tag", response);
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.v("tag", error.toString());
			}
		});
		sr.setTag("stringGet");
		MyApplication.getRequestQueue().add(sr);
	}
	
	private void stringPost()
	{
		String url = "http://www.baidu.com/s?";
		Listener<String> listener = new Listener<String>() {

			@Override
			public void onResponse(String response) {
				Log.v("tag", response);
			}
		};
		Response.ErrorListener errorListener = new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.v("tag", error.toString());
			}
		};
		StringRequest sr = new StringRequest(Method.POST, url, listener, errorListener) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> map = new HashMap<String, String>();
				map.put("wd", "android");
				return map;
			}
		};
		sr.setTag("stringPost");
		MyApplication.getRequestQueue().add(sr);
	}
	
	private void jsonGet()
	{
		String url = "http://m.weather.com.cn/atad/101230201.html";
		JsonObjectRequest jor = new JsonObjectRequest(url, null, new Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				Log.v("tag", response.toString());
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.v("tag", error.toString());
			}
		});
		jor.setTag("jsonGet");
		MyApplication.getRequestQueue().add(jor);
	}
	
	private void jsonPost()
	{
		String url = "http://fanyi.youdao.com/openapi.do?";
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("keyfrom", "lyh916");
		map.put("key", "1088118333");
		map.put("type", "data");
		map.put("doctype", "jsonp");
		map.put("callback", "show");
		map.put("version", "1.1");
		map.put("q", "API");
		JSONObject jsonRequest = new JSONObject(map);
		
		JsonObjectRequest jor = new JsonObjectRequest(Method.POST, url, jsonRequest, new Listener<JSONObject>() {

			@Override
			public void onResponse(JSONObject response) {
				Log.v("tag", response.toString());
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.v("tag", error.toString());
			}
		});
		jor.setTag("jsonPost");
		MyApplication.getRequestQueue().add(jor);
	}
	
	private void imageRequest()
	{
		String url = "http://avatar.csdn.net/8/5/5/3_lyh916.jpg";
		//第三第四个参数分别用于指定允许图片最大的宽度和高度,如果指定的网络图片的宽度或高度大于这里的最大值,则会对图片进行压缩,
		//指定成0的话就表示不管图片有多大,都不会进行压缩。
		ImageRequest imageRequest = new ImageRequest(url, new Listener<Bitmap>() {

			@Override
			public void onResponse(Bitmap response) {
				imageView.setImageBitmap(response);
			}
		}, 0, 0, Config.ARGB_8888, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				imageView.setImageResource(R.drawable.ic_launcher);
			}
		});
		MyApplication.getRequestQueue().add(imageRequest);
	}
	
	/*
	 * ImageLoader明显要比ImageRequest更加高效,因为它不仅可以帮我们对图片进行缓存,
	 * 还可以过滤掉重复的链接,避免重复发送请求。使用:
	 * 0.创建一个RequestQueue对象
	 * 1.创建一个ImageLoader对象
	 * 2.获取一个ImageListener对象
	 * 3.调用ImageLoader的get()方法加载网络上的图片
	 */
	private void imageLoader()
	{
		String url = "http://avatar.csdn.net/8/5/5/3_lyh916.jpg";
		ImageLoader imageLoader = new ImageLoader(MyApplication.getRequestQueue(), new BitmapCache());
		
		//第二个参数指定加载图片的过程中显示的图片,第三个参数指定加载图片失败的情况下显示的图片。
		ImageListener listener = ImageLoader.getImageListener(imageView, R.drawable.ic_launcher, R.drawable.ic_launcher);
		
		imageLoader.get(url, listener);
	}
	
	public class BitmapCache implements ImageCache {

		private LruCache<String, Bitmap> cache;
		
		public BitmapCache() {
			int maxSize = 10 * 1024 * 1024;//缓存图片的大小设置为10M
			cache = new LruCache<String, Bitmap>(maxSize) {  
	            @Override  
	            protected int sizeOf(String key, Bitmap bitmap) {  
	                return bitmap.getRowBytes() * bitmap.getHeight();  
	            }  
	        };
		}
		
		@Override
		public Bitmap getBitmap(String url) {
			return cache.get(url);
		}

		@Override
		public void putBitmap(String url, Bitmap bitmap) {
			cache.put(url, bitmap);
		}
	}
	
	/*
	 * NetworkImageView继承自ImageView,加入了加载网络图片的功能
	 * 使用:
	 * 0.创建一个RequestQueue对象
	 * 1.创建一个ImageLoader对象
	 * 2.在布局文件中添加一个NetworkImageView控件
	 * 3.在代码中获取该控件的实例
	 * 4.设置要加载的图片地址
	 */
	private void networkImageView()
	{
		String url = "http://avatar.csdn.net/8/5/5/3_lyh916.jpg";
		ImageLoader imageLoader = new ImageLoader(MyApplication.getRequestQueue(), new BitmapCache());
		
		NetworkImageView networkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
		networkImageView.setDefaultImageResId(R.drawable.ic_launcher);
		networkImageView.setErrorImageResId(R.drawable.ic_launcher);
		networkImageView.setImageUrl(url, imageLoader);
	}
}

3.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="100dp"
        android:layout_height="100dp" />
    
</LinearLayout>


你可能感兴趣的:(Volley)