오픈 소스 프레임 워 크 의 Volley

안 드 로 이 드 개발 에 있어 서 많은 오픈 소스 프레임 워 크 가 있 습 니 다. 예 를 들 어 Volley, xUtils, okhttp, afinal 등 오픈 소스 프레임 워 크 는 본인 이 안 드 로 이 드 를 접 한 지 얼마 되 지 않 았 기 때문에 접 한 오픈 소스 프레임 워 크 가 많 지 않 고 아 는 것 도 깊 지 않 습 니 다. 잘못된 말 이 있 으 면 어머니 가 저 를 때 리 세 요. Volley 는 구 글 공식 오픈 소스 프레임 워 크 입 니 다.다양한 네트워크 요청 (json 다운로드. 파일 업로드) 을 할 수 있 는 경량급 오픈 소스 프레임 워 크 입 니 다.
첫 번 째 단 계 는 응용 프로그램 에서 요청 대기 열 을 초기 화 합 니 다.
package com.longyue.customvolley2;

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

import android.app.Application;

public class VolleyApplication extends Application {

    /** * 01.         * 02.            AndroidMain.xml  * 03. */

    private static RequestQueue queue;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        queue=Volley.newRequestQueue(getApplicationContext());
    }

    //  
    public static RequestQueue getQueue(){
        return queue;
    }
}

두 번 째 단 계 는 3 급 캐 시 경로 (메모리, 소프트 참조, 디스크) 를 정의 합 니 다. 1: 메모리 캐 시 도구 류 는 LruCache 알고리즘 을 사용 합 니 다.
package com.longyue.volley;

import java.io.File;

import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;

public class VolleyBitmapCache implements ImageCache{
    private LruCache<String,Bitmap> cache;
    //         
    //       
    //    :
    private static VolleyBitmapCache mCache;
    private DiskLruCache mDisk;
    private VolleyBitmapCache() {
        //        LruCache      
        int maxSize=10*1024*1024;
        cache=new LruCache<String,Bitmap>(maxSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes()*value.getHeight();
            }
            //  LruCache         
            @Override
            protected void entryRemoved(boolean evicted, String key,
                    Bitmap oldValue, Bitmap newValue) {
                //  LruCache       ,      .
                if (evicted) {
                    ImageSoftReference.getInstance().putSoftReference(key,
                            oldValue);
                }
                super.entryRemoved(evicted, key, oldValue, newValue);
            }
        };
        //         
        mDisk = DiskLruCache.openCache(new File(Constant.cachepath),Constant.MAXBYTESIZE);
    }

    public static VolleyBitmapCache getInstance() {
        if (mCache == null) {
            mCache = new VolleyBitmapCache();
        }
        return mCache;
    }


    @Override
    public Bitmap getBitmap(String url) {
        //  LruCache  
        Log.e("ccccc","1111");
        Bitmap bitmap = cache.get(url);
        Log.e("ccccc","2222");
        if (bitmap == null) {
            //  SoftReference  
            bitmap = ImageSoftReference.getInstance().getSoftReference(url);
            //         .      
            if (bitmap == null) {
                // TODO:     :
                bitmap = mDisk.get(url);
            }
        }
        return bitmap;
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        //   
        cache.put(url, bitmap);
        mDisk.put(url, bitmap);
    }
    //        
    public void evictAll() {
        cache.evictAll();
        mDisk.clearCache();
    }

    //        
    public void evictOne(String key) {
        cache.remove(key);
    }
}

2: 소프트 인용 도구 류 있 으 나 마 나 없 는 것 이 없 는 것 보다 낫다
package com.longyue.volley;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class ImageSoftReference {

    //      ---->   .
    //        :   ---->       :   
    //  map    .----
    // SoftReference:   
    // Bitmap:  

    //         
    private Map<String, SoftReference<Bitmap>> mMap = null;

    private static ImageSoftReference mSoftReference;

    private ImageSoftReference() {
        mMap = new HashMap<String, SoftReference<Bitmap>>();
    }

    public static ImageSoftReference getInstance() {
        if (mSoftReference == null) {
            mSoftReference = new ImageSoftReference();
        }
        return mSoftReference;
    }

    //  Bitmap      
    public void putSoftReference(String key, Bitmap value) {
        mMap.put(key, new SoftReference<Bitmap>(value));
    }

    //          
    public Bitmap getSoftReference(String key) {
        //     "       "
        SoftReference<Bitmap> softReference = mMap.get(key);
        //    "           "?
        if (softReference != null) {
            return softReference.get();
        }
        return null;
    }
}

3 디스크 캐 시 도구 클래스
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */

package com.longyue.volley;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.android.volley.BuildConfig;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;



/** *         A simple disk LRU bitmap cache to illustrate how a disk cache would * be used for bitmap caching. A much more robust and efficient disk LRU cache * solution can be found in the ICS source code * (libcore/luni/src/main/java/libcore/io/DiskLruCache.java) and is preferable * to this simple implementation. */
public class DiskLruCache {
    private static final String TAG = "DiskLruCache";
    private static final String CACHE_FILENAME_PREFIX = "";
    private static final int MAX_REMOVALS = 4;
    private static final int INITIAL_CAPACITY = 32;
    private static final float LOAD_FACTOR = 0.75f;

    private final File mCacheDir;
    private int cacheSize = 0;
    private int cacheByteSize = 0;
    private final int maxCacheItemSize = 60; // 64 item default
    //        
    private long maxCacheByteSize = 1024 * 1024 * 5; // 5MB default
    private CompressFormat mCompressFormat = CompressFormat.JPEG;
    private int mCompressQuality = 70;

    private final Map<String, String> mLinkedHashMap = Collections
            .synchronizedMap(new LinkedHashMap<String, String>(
                    INITIAL_CAPACITY, LOAD_FACTOR, true));

    /** * A filename filter to use to identify the cache filenames which have * CACHE_FILENAME_PREFIX prepended. */
    private static final FilenameFilter cacheFileFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String filename) {
            return filename.startsWith(CACHE_FILENAME_PREFIX);
        }
    };

    /** * Used to fetch an instance of DiskLruCache. * * @param cacheDir * :         * @param maxByteSize * :             * @return */
    public static DiskLruCache openCache(File cacheDir, long maxByteSize) {
        //          ,     
        if (!cacheDir.exists()) {
            cacheDir.mkdir();
        }

        // Utils.getUsableSpace(cacheDir):              
        if (cacheDir.isDirectory() && cacheDir.canWrite()
                && Utils.getUsableSpace(cacheDir) > maxByteSize) {
            return new DiskLruCache(cacheDir, maxByteSize);
        }

        return null;
    }

    /** *     DiskLruCache      Constructor that should not be called directly, * instead use {@link DiskLruCache#openCache(Context, File, long)} which * runs some extra checks before creating a DiskLruCache instance. * * @param cacheDir * @param maxByteSize */
    private DiskLruCache(File cacheDir, long maxByteSize) {
        mCacheDir = cacheDir;
        maxCacheByteSize = maxByteSize;
    }

    /** * Add a bitmap to the disk cache.              * * @param key * :bitmap        A unique identifier for the bitmap. * @param data * :       The bitmap to store. */
    public void put(String key, Bitmap data) {
        synchronized (mLinkedHashMap) {
            if (mLinkedHashMap.get(key) == null) {
                try {
                    final String file = createFilePath(mCacheDir, key);
                    if (writeBitmapToFile(data, file)) {
                        put(key, file);
                        flushCache();
                    }
                } catch (final FileNotFoundException e) {
                    Log.e(TAG, "Error in put: " + e.getMessage());
                } catch (final IOException e) {
                    Log.e(TAG, "Error in put: " + e.getMessage());
                }
            }
        }
    }

    private void put(String key, String file) {
        mLinkedHashMap.put(key, file);
        cacheSize = mLinkedHashMap.size();
        cacheByteSize += new File(file).length();
    }

    /** *         .                         ,        bitmap. Flush the cache, * removing oldest entries if the total size is over the specified cache * size. Note that this isn't keeping track of stale files in the cache * directory that aren't in the HashMap. If the images and keys in the disk * cache change often then they probably won't ever be removed. */
    private void flushCache() {
        Entry<String, String> eldestEntry;
        File eldestFile;
        long eldestFileSize;
        int count = 0;

        while (count < MAX_REMOVALS
                && (cacheSize > maxCacheItemSize || cacheByteSize > maxCacheByteSize)) {
            eldestEntry = mLinkedHashMap.entrySet().iterator().next();
            eldestFile = new File(eldestEntry.getValue());
            eldestFileSize = eldestFile.length();
            mLinkedHashMap.remove(eldestEntry.getKey());
            eldestFile.delete();
            cacheSize = mLinkedHashMap.size();
            cacheByteSize -= eldestFileSize;
            count++;
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "flushCache - Removed cache file, " + eldestFile
                        + ", " + eldestFileSize);
            }
        }
    }

    /** * Get an image from the disk cache.         key      * * @param key * The unique identifier for the bitmap * @return The bitmap or null if not found */
    public Bitmap get(String key) {
        synchronized (mLinkedHashMap) {
            final String file = mLinkedHashMap.get(key);
            if (file != null) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Disk cache hit");
                }
                return BitmapFactory.decodeFile(file);
            } else {
                final String existingFile = createFilePath(mCacheDir, key);
                if (new File(existingFile).exists()) {
                    put(key, existingFile);
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "Disk cache hit (existing file)");
                    }
                    return BitmapFactory.decodeFile(existingFile);
                }
            }
            return null;
        }
    }

    /** * Checks if a specific key exist in the cache.   key          * * @param key * The unique identifier for the bitmap * @return true if found, false otherwise */
    public boolean containsKey(String key) {
        // See if the key is in our HashMap
        if (mLinkedHashMap.containsKey(key)) {
            return true;
        }

        // Now check if there's an actual file that exists based on the key
        final String existingFile = createFilePath(mCacheDir, key);
        if (new File(existingFile).exists()) {
            // File found, add it to the HashMap for future use
            put(key, existingFile);
            return true;
        }
        return false;
    }

    /** *           bitmap Removes all disk cache entries from this instance cache * dir */
    public void clearCache() {
        DiskLruCache.clearCache(mCacheDir);
    }

    /** * Removes all disk cache entries from the application cache directory in * the uniqueName sub-directory.     key      * * @param context * The context to use * @param uniqueName * A unique cache directory name to append to the app cache * directory */
    public static void clearCache(Context context, String uniqueName) {
        File cacheDir = getDiskCacheDir(context, uniqueName);
        clearCache(cacheDir);
    }

    /** *              (  ) Removes all disk cache entries from the given * directory. This should not be called directly, call * {@link DiskLruCache#clearCache(Context, String)} or * {@link DiskLruCache#clearCache()} instead. * * @param cacheDir * The directory to remove the cache files from */
    private static void clearCache(File cacheDir) {
        final File[] files = cacheDir.listFiles(cacheFileFilter);
        for (int i = 0; i < files.length; i++) {
            files[i].delete();
        }
    }

    /** * Get a usable cache directory (external if available, internal otherwise). *          * * @param context * The context to use * @param uniqueName * A unique directory name to append to the cache dir * @return The cache dir */
    public static File getDiskCacheDir(Context context, String uniqueName) {

        // Check if media is mounted or storage is built-in, if so, try and use
        // external cache dir
        // otherwise use internal cache dir
        final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
                || !Utils.isExternalStorageRemovable() ? Utils
                .getExternalCacheDir(context).getPath() : context.getCacheDir()
                .getPath();

        return new File(cachePath + File.separator + uniqueName);
    }

    /** *            Creates a constant cache file path given a target cache * directory and an image key.          * * @param cacheDir * @param key * @return */
    public static String createFilePath(File cacheDir, String key) {
        try {
            // Use URLEncoder to ensure we have a valid filename, a tad hacky
            // but it will do for
            // this example
            return cacheDir.getAbsolutePath() + File.separator
                    + CACHE_FILENAME_PREFIX
                    + URLEncoder.encode(key.replace("*", ""), "UTF-8");
        } catch (final UnsupportedEncodingException e) {
            Log.e(TAG, "createFilePath - " + e);
        }

        return null;
    }

    /** * Create a constant cache file path using the current cache directory and * an image key. * * @param key * @return */
    public String createFilePath(String key) {
        return createFilePath(mCacheDir, key);
    }

    /** *              Sets the target compression format and quality for images * written to the disk cache. * * @param compressFormat * @param quality */
    public void setCompressParams(CompressFormat compressFormat, int quality) {
        mCompressFormat = compressFormat;
        mCompressQuality = quality;
    }

    /** *                Writes a bitmap to a file. Call * {@link DiskLruCache#setCompressParams(CompressFormat, int)} first to set * the target bitmap compression and format.           ,           . * * @param bitmap * @param file * @return */
    private boolean writeBitmapToFile(Bitmap bitmap, String file)
            throws IOException, FileNotFoundException {

        OutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file),
                    Utils.IO_BUFFER_SIZE);
            // mCompressFormat:         -->jpeg;
            // mCompressQuality:     .
            return bitmap.compress(mCompressFormat, mCompressQuality, out);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

4. 두 도구 류 와 상수
//   
package com.longyue.volley;

import java.io.File;

import android.os.Environment;

public class Constant {
    //       
    public static String cachepath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "    ";
    public static long MAXBYTESIZE =8*1024 * 1024;
}


//utils   
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */

package com.longyue.volley;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

/** * Class containing some static utility methods. */
public class Utils {
    public static final int IO_BUFFER_SIZE = 8 * 1024;

    private Utils() {
    };

    /** * Workaround for bug pre-Froyo, see here for more info: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html */
    public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (hasHttpConnectionBug()) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    /** * Get the size in bytes of a bitmap. * * @param bitmap * @return size in bytes */
    @SuppressLint("NewApi")
    public static int getBitmapSize(Bitmap bitmap) {
        //   sdk        (API 12)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        }
        // Pre HC-MR1
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    /** * Check if external storage is built-in or removable. * * @return True if external storage is removable (like an SD card), false * otherwise. */
    @SuppressLint("NewApi")
    public static boolean isExternalStorageRemovable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return Environment.isExternalStorageRemovable();
        }
        return true;
    }

    /** * Get the external app cache directory. * * @param context * The context to use * @return The external cache dir */
    @SuppressLint("NewApi")
    public static File getExternalCacheDir(Context context) {
        if (hasExternalCacheDir()) {
            return context.getExternalCacheDir();
        }

        // Before Froyo we need to construct the external cache dir ourselves
        final String cacheDir = "/Android/data/" + context.getPackageName()
                + "/cache/";
        return new File(Environment.getExternalStorageDirectory().getPath()
                + cacheDir);
    }

    /** * Check how much usable space is available at a given path.               * * @param path * The path to check * @return The space available in bytes */
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public static long getUsableSpace(File path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return path.getUsableSpace();
        }
        final StatFs stats = new StatFs(path.getPath());
        return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
    }

    /** * Get the memory class of this device (approx. per-app memory limit) * * @param context * @return */
    public static int getMemoryClass(Context context) {
        return ((ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    }

    /** * Check if OS version has a http URLConnection bug. See here for more * information: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html * * @return */
    public static boolean hasHttpConnectionBug() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO;
    }

    /** * Check if OS version has built-in external cache dir method. * * @return */
    public static boolean hasExternalCacheDir() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    /** * Check if ActionBar is available. * * @return */
    public static boolean hasActionBar() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }
}

세 번 째 단계 2 차 봉인 Volley 1: 인터페이스 리 셋 감청
package com.longyue.volley;

import com.android.volley.Response;
import com.android.volley.VolleyError;


/** *                 *        * @author yuan * * @param <T> */

public abstract class VolleyHandler<T> {


    public Response.Listener<T> reqLis;
    public Response.ErrorListener reqErr;

    public VolleyHandler() {
        //       
        reqLis = new reqListener();
        reqErr = new reqErrorListener();
    }

    public abstract void reqSuccess(T response);

    public abstract void reqError(String error);

    /** *        * * @author yuan * */
    public class reqListener implements Response.Listener<T> {

        @Override
        public void onResponse(T response) {
            //                reqSuccess
            reqSuccess(response);
        }
    }

    /** *        * * @author yuan * */
    public class reqErrorListener implements Response.ErrorListener {

        @Override
        public void onErrorResponse(VolleyError error) {
            //                ReqError
            reqError(error.getMessage());
        }
    }
}

2 패키지 파일 업로드 요청 대기 열
package com.longyue.volley;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

public class MultipartRequest extends Request<String> {

    private MultipartEntity entity = new MultipartEntity();

    private final Response.Listener<String> mListener;

    private List<File> mFileParts;
    private String mFilePartName;
    private Map<String, String> mParams;
    /** *      * @param url * @param errorListener * @param listener * @param filePartName * @param file * @param params */
    public MultipartRequest(String url, Response.ErrorListener errorListener,
            Response.Listener<String> listener, String filePartName, File file,
            Map<String, String> params) {
        super(Method.POST, url, errorListener);

        mFileParts = new ArrayList<File>();
        if (file != null) {
            mFileParts.add(file);
        }
        mFilePartName = filePartName;
        mListener = listener;
        mParams = params;
        buildMultipartEntity();
    }
    /** *     ,    key * @param url * @param errorListener * @param listener * @param filePartName * @param files * @param params */
    public MultipartRequest(String url, Response.ErrorListener errorListener,
            Response.Listener<String> listener, String filePartName,
            List<File> files, Map<String, String> params) {
        super(Method.POST, url, errorListener);
        mFilePartName = filePartName;
        mListener = listener;
        mFileParts = files;
        mParams = params;
        buildMultipartEntity();
    }

    private void buildMultipartEntity() {
        if (mFileParts != null && mFileParts.size() > 0) {
            for (File file : mFileParts) {
                entity.addPart(mFilePartName, new FileBody(file));
            }
        }

        try {
            if (mParams != null && mParams.size() > 0) {
                for (Map.Entry<String, String> entry : mParams.entrySet()) {
                    entity.addPart(
                            entry.getKey(),
                            new StringBody(entry.getValue(), Charset
                                    .forName("UTF-8")));
                }
            }
        } catch (UnsupportedEncodingException e) {
            VolleyLog.e("UnsupportedEncodingException");
        }
    }

    @Override
    public String getBodyContentType() {
        return entity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            entity.writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        if (VolleyLog.DEBUG) {
            if (response.headers != null) {
                for (Map.Entry<String, String> entry : response.headers
                        .entrySet()) {
                    VolleyLog.d(entry.getKey() + "=" + entry.getValue());
                }
            }
        }

        String parsed;
        try {
            parsed = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed,
                HttpHeaderParser.parseCacheHeaders(response));
    }


    /* * (non-Javadoc) * * @see com.android.volley.Request#getHeaders() */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        VolleyLog.d("getHeaders");
        Map<String, String> headers = super.getHeaders();

        if (headers == null || headers.equals(Collections.emptyMap())) {
            headers = new HashMap<String, String>();
        }
        return headers;
    }

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }
}

3 요청 방법 봉인
package com.longyue.volley;

import java.io.File;
import java.util.Map;

import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.longyue.customvolley2.VolleyApplication;


/** * @author xuenan * */
public class VolleyHttpRequest{


    /** 1. * StringRequest GET   * @param url    * @param volleyRequest      */
    public static void String_request(String url,VolleyHandler<String> volleyRequest){
        Volley_StringRequest(Method.GET, url,null, volleyRequest);
    }

    /** 1. * StringRequset POST   * @param url    * @param map    * @param volleyRequest      */
    public static void String_request(String url,final Map<String,String> map,VolleyHandler<String> volleyRequest){
        Volley_StringRequest(Method.POST,url,map,volleyRequest);
    }
    /**Volley_UploadImage_Request POST   * @param url    * @param params      * @param volleyRequest      * @param fileName     * @param file        */
    public static void File_Upload_request(String url,final Map<String,String> params,VolleyHandler<String> volleyRequest,String fileName,File file){
        Volley_UploadImage_Request(url, params, volleyRequest, fileName, file);
    }
    /**1. *    StringRequest      * @param method    * @param url    * @param params    * @param volleyRequest      */
    private static void Volley_StringRequest(int method,String url,final Map<String,String> params,VolleyHandler<String> volleyRequest){
        StringRequest stringrequest=new StringRequest(method, url,volleyRequest.reqLis,volleyRequest.reqErr){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        stringrequest.setTag("stringrequest");
        VolleyApplication.getQueue().add(stringrequest);
    }

    /**2  MultipartRequest           * @param url * @param params    * @param volleyRequest      * @param fileName     * @param file    */
    private static void Volley_UploadImage_Request(String url,final Map<String,String> params,VolleyHandler<String> volleyRequest,String fileName,File file){
        MultipartRequest imageRequest=new MultipartRequest(url, volleyRequest.reqErr,volleyRequest.reqLis,fileName, file, params);
        imageRequest.setTag("imageRequest");
        VolleyApplication.getQueue().add(imageRequest);
    }
    /**2. * JsonObjectRequest GET    * @param url      * @param volleyRequest        */
    public static void JsonObject_Request(String url,VolleyHandler<JSONObject> volleyRequest){
         Volley_JsonObjectRequest(Method.GET,url,null,volleyRequest);
    }

    /**2 * JsonObjectRequest POST    * @param url      * @param jsonObject      * @param volleyRequest        */
    public static void JsonObject_Request(String url,JSONObject jsonObject,VolleyHandler<JSONObject> volleyRequest){
        Volley_JsonObjectRequest(Method.POST,url,jsonObject,volleyRequest);
    }

    /**2. *    JsonObjectRequest      * @param method    * @param url    * @param jsonObject    * @param volleyRequest        */
    private static void Volley_JsonObjectRequest(int method,String url,JSONObject jsonObject,VolleyHandler<JSONObject> volleyRequest){
         JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(method,url,jsonObject,volleyRequest.reqLis,volleyRequest.reqErr);
         jsonObjectRequest.setTag("jsonObjectRequest");
         VolleyApplication.getQueue().add(jsonObjectRequest);
    }


    /**3. * ImageRequest           * @param url    * @param volleyRequest      */
    public static void Image_request(String url,VolleyHandler<Bitmap> volleyRequest){
        Volley_ImageRequest(url, 0, 0, volleyRequest);
    }

    /**3. * ImageRequest        * @param url    * @param maxWidth      * @param maxHeight      * @param volleyRequest      */
    public static void Image_request(String url,int maxWidth,int maxHeight,VolleyHandler<Bitmap> volleyRequest){
        Volley_ImageRequest(url, maxWidth, maxHeight, volleyRequest);
    }


    /**3. *    ImageRequest      * @param url    * @param maxWidth      * @param maxHeight      * @param volleyRequest        */
    private static void Volley_ImageRequest(String url,int maxWidth,int maxHeight,VolleyHandler<Bitmap> volleyRequest){
        ImageRequest imageRequest=new ImageRequest(url,volleyRequest.reqLis, maxWidth, maxHeight,Config.RGB_565,volleyRequest.reqErr);
        imageRequest.setTag("imageRequest");
        VolleyApplication.getQueue().add(imageRequest);
    }


    /** * 4. *           * @param url * @param imageListener * @param maxWidth * @param maxHidth */
    public static void Image_Loader(String url,ImageListener imageListener,int maxWidth,int maxHidth){
        Volley_ImageLoader(url, imageListener, maxWidth, maxHidth);
    }


    /** 4. *    ,     * @param url    * @param imageListener      */
    public static void Image_Loader(String url,ImageListener imageListener){
        Volley_ImageLoader(url,imageListener,0,0);
    }


    /** 4. *    ImageLoader    * @param url    * @param imageListener      * @param maxWidth * @param maxHidth */
    private static void Volley_ImageLoader(String url,ImageListener imageListener,int maxWidth,int maxHidth){
                //         :   imageLoader   
                //    LruBitmap + ImageCache   
                //      
        ImageLoader imageLoader = new ImageLoader(VolleyApplication.getQueue(),
                        VolleyBitmapCache.getInstance());
                //           (    ,    )   imageView
        imageLoader.get(url, imageListener,maxWidth,maxHidth);
    }
}

이 정도 면 프로 그래 밍 의 매력 을 즐 길 수 있 을 것 같 아 요.
데모 다운로드

좋은 웹페이지 즐겨찾기