1. 程式人生 > >Volley的Get、Post方式(JsonObjectRequest、StringRequest)以及Volley獲取圖片的3種方式

Volley的Get、Post方式(JsonObjectRequest、StringRequest)以及Volley獲取圖片的3種方式

volley use utf-8 設置 ica static toast 隊列 getheight

activity_main.xml 裏面什麽也沒有

AndroidManifest.xml(重點是android:name="com.example.volley.MyApplication")

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

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="18" />

    <application
        android:name="com.example.volley.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <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>

    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

MyApplication

package com.example.volley;

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

import android.app.Application;

public class MyApplication extends Application {
	public static RequestQueue queue;

	/** 一旦創建就創建RequestQueue請求隊列 */
	@Override
	public void onCreate() {
		super.onCreate();
		queue = Volley.newRequestQueue(getApplicationContext());

	}

	/** 對外提供靜態的方法 */
	public static RequestQueue getHttpRequestQueue() {
		return queue;
	}
}

MainActivity

package com.example.volley;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
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.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {

	/**
	 * 關聯activity。退出之後取消全部的網絡請求,釋放資源
	 */
	@Override
	protected void onStop() {
		super.onStop();
		MyApplication.getHttpRequestQueue().cancelAll("abcGet");

	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
//		volley_get();
		volley_post();
	}

	/**
	 * get請求方式
	 */
	private void volley_get() {
		
		/**
		 * String類型
		 */
		String url = "http://www.imooc.com/api/teacher?

type=4&num=30"; StringRequest request = new StringRequest(Method.GET, url, new Listener<String>() { @Override public void onResponse(String arg0) { //返回正確後的操作 Log.e("TAG", ""+arg0); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { } }); // 設置標簽 request.setTag("abcGet"); MyApplication.getHttpRequestQueue().add(request); MyApplication.getHttpRequestQueue().start(); /** * JsonObjectRequest類型 由於get參數已經在url寫好了,所以傳空就可以 */ JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET, url, null, new Listener<JSONObject>() { @Override public void onResponse(JSONObject arg0) { Toast.makeText(MainActivity.this, arg0.toString(), 0) .show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { } }); // 設置標簽 jsonObjectRequest.setTag("bcdGet"); MyApplication.getHttpRequestQueue().add(jsonObjectRequest); MyApplication.getHttpRequestQueue().start(); /** * 還有jsonArray方式,這裏省略了。。。 */ } /** * post請求方式 */ private void volley_post() { /** * StringRequest---post方式 */ String url = "http://www.imooc.com/api/teacher?

"; StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() { @Override public void onResponse(String arg0) { Log.e("TAG", ""+arg0); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { //傳遞參數 Map<String, String> map = new HashMap<String, String>(); map.put("type", "4"); map.put("num", "30"); return map; } }; // 設置標簽 request.setTag("abcPost"); MyApplication.getHttpRequestQueue().add(request); MyApplication.getHttpRequestQueue().start(); /** * jsonObject--post方式 */ HashMap<String, String> map = new HashMap<String, String>(); map.put("type", "4"); map.put("num", "30"); // 將map轉為jsonObject對象 JSONObject object = new JSONObject(map); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.POST, url, object, new Listener<JSONObject>() { @Override public void onResponse(JSONObject arg0) { Log.e("TAG", arg0.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { } }); // 設置標簽 jsonObjectRequest.setTag("bcdPost"); MyApplication.getHttpRequestQueue().add(jsonObjectRequest); MyApplication.getHttpRequestQueue().start(); } }


*************************************************下載網絡圖片**********************************************

AndroidManifest.xml(重點是 android:name="com.example.volleyimagedemo.MyApplication")

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

    <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="18" />

    <application
        android:name="com.example.volleyimagedemo.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <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>

    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>
activity_main.xml

<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"
    tools:context="com.example.volleyimagedemo.MainActivity" >

    <!-- 方式一 -->
    <ImageView
        android:id="@+id/imageview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
     <!-- 方式二 -->
    <ImageView
        android:id="@+id/imageview2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <!-- 方式三 -->
    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </com.android.volley.toolbox.NetworkImageView>
    
    

</LinearLayout>

MyApplication

package com.example.volleyimagedemo;

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

import android.app.Application;

public class MyApplication extends Application {
	public static RequestQueue queue;

	@Override
	public void onCreate() {
		super.onCreate();
		queue = Volley.newRequestQueue(getApplicationContext());

	}

	public static RequestQueue getHttpRequestQueue() {

		return queue;
	}
}

BitMapCache

package com.example.volleyimagedemo;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class BitMapCache implements ImageCache{

	public LruCache<String, Bitmap> cache;
	//超過10兆,自己主動回收
	public int max = 10*1024*1024;
	public BitMapCache(){
		cache = new LruCache<String, Bitmap>(max){
			@Override
			protected int sizeOf(String key, Bitmap value) {
				return value.getRowBytes()*value.getHeight();
			}
		};
	}
	@Override
	public Bitmap getBitmap(String arg0) {
		return cache.get(arg0);
	}

	@Override
	public void putBitmap(String arg0, Bitmap arg1) {
		cache.put(arg0, arg1);
	}
	

}

MainActivity

package com.example.volleyimagedemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.widget.ImageView;

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.ImageListener;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;

public class MainActivity extends Activity {
	private ImageView imageview1;
	private ImageView imageview2;
	private NetworkImageView networkImageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		/** 獲取控件、圖片url地址 */
		imageview1 = (ImageView) findViewById(R.id.imageview1);
		imageview2 = (ImageView) findViewById(R.id.imageview2);
		networkImageView = (NetworkImageView) findViewById(R.id.networkImageview);
		String url = "http://img.mukewang.com/55237dcc0001128c06000338-300-170.jpg";

		/**
		 * 下載圖片的另外一種方式ImageLoader+BitMapCache
		 */
		// imageCache單肚使用是不到緩存效果,須要結合lruCache
		ImageLoader imageLoader1 = new ImageLoader(
				MyApplication.getHttpRequestQueue(), new BitMapCache());
		networkImageView.setDefaultImageResId(R.drawable.ic_launcher);
		networkImageView.setErrorImageResId(R.drawable.ic_launcher);
		networkImageView.setImageUrl(url, imageLoader1);

		/**
		 * 下載圖片的第三種種方式
		 */
		ImageLoader imageLoader2 = new ImageLoader(
				MyApplication.getHttpRequestQueue(), new BitMapCache());
		// view視圖,默認的圖片,錯誤的圖片
		ImageListener listener = imageLoader1.getImageListener(imageview2,
				R.drawable.ic_launcher, R.drawable.ic_launcher);
		imageLoader2.get(url, listener);

		/**
		 * 下載網絡圖片的第一種方式ImageRequest
		 */
		// // 0 是原圖的方式載入--Config.RGB_565原圖
		ImageRequest imageRequest = new ImageRequest(url,
				new Listener<Bitmap>() {
					//
					@Override
					public void onResponse(Bitmap arg0) {
						imageview1.setImageBitmap(arg0);
					}
				}, 0, 0, Config.RGB_565, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						imageview1
								.setBackgroundResource(R.drawable.ic_launcher);
					}
				});

		MyApplication.getHttpRequestQueue().add(imageRequest);
		MyApplication.getHttpRequestQueue().start();
	}

}



Volley的Get、Post方式(JsonObjectRequest、StringRequest)以及Volley獲取圖片的3種方式