使用okhttp加载服务器数据,Glide加载图片

使用okhttp加载服务器数据,Glide加载图片

  1. 网项目中导入glide-3.6.1.jar okhttp-3.2.0.jar okio-1.11.0.jar架包;
  2. GlideCache实现GlideModule类,这个类主要实现的是图片缓存的路劲和缓存的大小

图片缓存类实现

public class GlideCache implements GlideModule{

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        // TODO Auto-generated method stub
        builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
        File storageDirectory=Environment.getExternalStorageDirectory();
        String download=storageDirectory+ File.separator
                + "文件夹名称"  + File.separator;
        int cacheSize=100*1000*1000;
        builder.setDiskCache(new DiskLruCacheFactory(download, cacheSize));
    }

    @Override
    public void registerComponents(Context arg0, Glide arg1) {
        // TODO Auto-generated method stub

    }

}

3、实现图片缓存的数据后再AndroidManifest.xml文件中进行注册

 data 
            android:name="包名.GlideCache"
            android:value="GlideModule"
            />

4、建立一个公共的图片下载工具类,方便下载图片调用

public class ImageLoader {
    /**
     * 图片下载无缓存
     * 
     * @param context
     *            上下文
     * @param url
     *            图片地址(是gif显示gif文件)
     * @param imageView
     *            显示图片控件
     */
    public static void loadImageNoCache(Context context, String url,
            ImageView imageView) {
        if (url != null) {
            if (url.contains(".gif")) {
                Glide.with(context).load(url).asGif()
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(imageView);
            } else {
                Glide.with(context).load(url).crossFade()
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(imageView);
            }
        }
    }

    /**
     * 图片下载有缓存
     * 
     * @param context
     *            上下文
     * @param url
     *            图片地址(是gif显示gif文件)
     * @param imageView
     *            显示图片控件
     */
    public static void loadImageHaveCache(Context context, String url,
            ImageView imageView) {
        if (url.contains(".gif")) {
            Glide.with(context).load(url).asGif()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(imageView);
        } else {
            Glide.with(context).load(url)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(imageView);
        }
    }

    /**
     * 加载资源文件中的图片
     * 
     * @param context
     *            上下文
     * @param resourseId
     *            资源文件ID
     * @param imageView
     *            显示图片控件
     */
    public static void showImage(Context context, int resourseId,
            ImageView imageView) {
        Glide.with(context).load(resourseId)
                .diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
    }
    /**
     * 加载资源文件中的图片
     * 
     * @param context
     *            上下文
     * @param resourseId
     *            资源文件ID
     * @param imageView
     *            显示图片控件
     */
    public static void showImageGif(Context context, int resourseId,
            ImageView imageView) {
        Glide.with(context).load(resourseId).asGif()
                .diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
    }
    /**
     * 加载资源文件中的图片
     * 
     * @param context
     *            上下文
     * @param resourseId
     *            资源文件ID
     * @param imageView
     *            显示图片控件
     */
    public static void showOneGif(Context context, int resourseId,
            ImageView imageView) {
        Glide.with(context).load(resourseId).into(imageView);
    }

    /**
     * @param context
     *            上下文
     * @param url
     *            图片地址
     * @return 根据地址返回bitmap文件
     */
    public static void getBitmap(final Context context, final String url,
            final BitmapCallBack callBack) {
        Glide.with(context).load(url).asBitmap()
                .into(new SimpleTarget() {
                    @Override
                    public void onResourceReady(Bitmap bitmap,
                            @SuppressWarnings("rawtypes") GlideAnimation anim) {
                        callBack.callback(bitmap);
                    }
                });
    }

    public interface BitmapCallBack {
        void callback(Bitmap bitmap);
    }

}

5、建立一个使用okhttp访问服务器的公共的get和post方法

/**
 * Created by Administrator on 2017/4/24 0024. 访问服务器基类
 */

public class NetCall {

    public static OkHttpClient client;
    public static NetCall instance;

    public static NetCall getInstance(Context context) {
        if (instance == null) {
            synchronized (NetCall.class) {
                if (instance == null) {
                    instance = new NetCall(context);
                    return instance;
                }
            }
        }
        return instance;
    }

    public NetCall(Context context) {
        // 设置okhttp框架信任所有证书,访问到https地址
        OkHttpClient.Builder build = new OkHttpClient.Builder();
        build.sslSocketFactory(createSSLSocketFactory());
        build.hostnameVerifier(new TrustAllHostnameVerifier());
        client = build.cache(new Cache(context.getCacheDir(), 200))
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS).build();
    }

    /**
     * 信任所有证书,返回true
     */
    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssl = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { new TrustAllCerts() },
                    new SecureRandom());
            ssl = sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return ssl;
    }

    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    /**
     * okhttp GET()方法访问
     * 
     * @param params
     *            访问服务器参数
     * @param callBack
     *            监听服务器返回数据
     */
    public  void get(Map params,
            final UIReFlashHandle handle) {
        StringBuilder stringBuilder = new StringBuilder();
        if (params != null && params.size() > 0) {
            Set> set = params.entrySet();
            for (Map.Entry entry : set) {
                stringBuilder.append(entry.getKey());
                stringBuilder.append("=");
                try {
                    stringBuilder.append(URLEncoder.encode(entry.getValue(),
                            "utf-8"));
                    stringBuilder.append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            final Request request = new Request.Builder()
                    .url(Config.URL + stringBuilder.toString()).get().build();
            // 访问接口参数打印
            LogUtils.LogURL("访问服务器参数", request.url().toString());
            client.newCall(request).enqueue(new Callback() {

                @SuppressWarnings("unchecked")
                @Override
                public void onResponse(Call arg0, Response response)
                        throws IOException {
                    if (response.isSuccessful() && handle != null) {
                        String json = response.body().string();
                        LogUtils.Log("返回服务器数据", json);
                        if (!TextUtils.isEmpty(json)) {
                            try {
                                JSONObject object = new JSONObject(json);
                                switch (object.getInt(Config.STATUS)) {
                                case Config.SUCCESS:
                                    // status==1 获取信息成功
                                    Gson gson = new Gson();
                                    Type type = handle.type;
                                    if (type == String.class) {
                                        Message message = new Message();
                                        message.what = UIReFlashHandle.SUCCESS;
                                        message.obj = (T) json;
                                        handle.sendMessage(message);
                                    } else {
                                        T t = gson.fromJson(json, type);
                                        Message message = new Message();
                                        message.what = UIReFlashHandle.SUCCESS;
                                        message.obj = t;
                                        handle.sendMessage(message);
                                    }
                                    break;
                                case Config.FAILED:
                                    // status==0 获取失败,提示各种信息
                                    Message message = new Message();
                                    message.what = UIReFlashHandle.FAILED;
                                    message.obj = object.getString(Config.MSG);
                                    handle.sendMessage(message);
                                    break;

                                default:
                                    break;
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        } else {
                            Message message = new Message();
                            message.what = UIReFlashHandle.FAILED;
                            message.obj = "获取信息失败";
                            handle.sendMessage(message);
                        }
                    }
                }

                @Override
                public void onFailure(Call arg0, IOException arg1) {
                    // TODO Auto-generated method stub
                    Message message = new Message();
                    message.what = UIReFlashHandle.NONET;
                    message.obj = "网络问题";
                    LogUtils.Log("返回服务器数据", "网络问题");
                    handle.sendMessage(message);
                }
            });
        }
    }

    /**
     * okhttp POST()方法访问
     * 
     * @param params
     *            访问服务器参数
     * @param callBack
     *            监听服务器返回数据
     * @param 
     *            返回的数据类型
     */
    public  void post(Map params,
            final UIReFlashHandle handle) {
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        final Request request = new Request.Builder().url(Config.URL)
                .post(builder.build()).build();
        // 访问数据打印
        LogUtils.LogURL("访问服务器参数", request.url().toString() + params.toString());
        client.newCall(request).enqueue(new Callback() {

            @SuppressWarnings("unchecked")
            @Override
            public void onResponse(Call arg0, Response response)
                    throws IOException {
                if (response.isSuccessful() && handle != null) {
                    String json = response.body().string();
                    LogUtils.Log("返回服务器数据", json.toString());
                    if (!TextUtils.isEmpty(json)) {
                        try {
                            JSONObject object = new JSONObject(json);
                            switch (object.getInt(Config.STATUS)) {
                            case Config.SUCCESS:
                                // status==1 获取信息成功
                                Gson gson = new Gson();
                                Type type = handle.type;
                                if (type == String.class) {
                                    Message message = new Message();
                                    message.what = UIReFlashHandle.SUCCESS;
                                    message.obj = (T) json;
                                    handle.sendMessage(message);
                                } else {
                                    T t = gson.fromJson(json, type);
                                    Message message = new Message();
                                    message.what = UIReFlashHandle.SUCCESS;
                                    message.obj = t;
                                    handle.sendMessage(message);
                                }
                                break;
                            case Config.FAILED:
                                // status==0 获取失败,提示各种信息
                                Message message = new Message();
                                message.what = UIReFlashHandle.FAILED;
                                message.obj = object.getString(Config.MSG);
                                handle.sendMessage(message);
                                break;

                            default:
                                break;
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    } else {
                        Message message = new Message();
                        message.what = UIReFlashHandle.FAILED;
                        message.obj = "获取用户失败,请重试";
                        handle.sendMessage(message);
                    }
                }
            }

            @Override
            public void onFailure(Call arg0, IOException arg1) {
                // TODO Auto-generated method stub
                Message message = new Message();
                message.what = UIReFlashHandle.NONET;
                message.obj = "网络问题";
                handle.sendMessage(message);
            }
        });
    }

}

6、因为okhttp获取服务器的内容不能再主线程中使用,其中的UIReFlashHandle的方法就是建立一个子线程,用于数据显示在页面之中

public class UIReFlashHandle<T> extends Handler {
    // 解析数据成功
    public static final int SUCCESS = 1;
    // 解析数据失败
    public static final int FAILED = 0;
    // 网络出错
    public static final int NONET = -1;

    protected MyDataListener listener;

    protected Type type;

    public UIReFlashHandle(MyDataListener listener, Type type) {
        this.listener = listener;
        this.type = type;
    }

    /*
     * @param msg
     * 
     * @Descrition:
     */
    @SuppressWarnings("unchecked")
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case SUCCESS:
            listener.onSuccess((T) msg.obj);
            break;
        case FAILED:
            listener.onFailed((String) msg.obj);
            break;
        case NONET:
            listener.onErrorNet((String) msg.obj);
            break;

        default:
            break;
        }
    }

}
/**
 * @author Administrator
 * @param    数据类型
 * @time:2017-5-26 下午2:39:09
 * @Descrition:  返回数据监听
 */
public interface MyDataListener {
     abstract void onErrorNet(String msg);
     abstract void onFailed(String msg);
     abstract void onSuccess(T t);

}

7、具体的访问服务器数据方法如下

private void GetData() {
        HashMaphashMap=new HashMap<>();
        hashMap.put("参数", "参数值");
        ...
        NetCall.getInstance(this).get(Select,
                new UIReFlashHandle<>(new MyDataListener<返回值解析的基本类>() {

                    @Override
                    public void onErrorNet(String msg) {
                        //无网络时提示信息
                    }

                    @Override
                    public void onFailed(String msg) {
                        //查询服务器数据出错
                    }

                    @Override
                    public void onSuccess(SelectLinkageBean t) {
                        //查询服务器数据成功
                        }

                    }
                }, 返回值解析的基本类.class));
    }

你可能感兴趣的:(android,Glide,okhttp)