开源框架OKHttp的使用02-封装后的OkHttpUtils

一、简介

参考文章:http://blog.csdn.net/lmj623565791/article/details/49734867
简化了OKHttp直接进行一些操作的步骤。集成后的框架下载:
https://github.com/hongyangAndroid/okhttp-utils

二、使用场景

一般的get请求
一般的post请求
基于Http的文件上传
文件下载
上传下载的进度回调
加载图片
支持请求回调,直接返回对象、对象集合
支持session的保持
支持自签名网站https的访问,提供方法设置下证书就行
支持取消某个请求

三、示例代码

开源框架OKHttp的使用02-封装后的OkHttpUtils_第1张图片

package com.zhy.sample_okhttp;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

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

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;

public class MainActivity extends Activity {


    private static final String TAG = "MainActivity";

    private TextView mTv;
    private ImageView mImageView;
    private ProgressBar mProgressBar;

    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(Request request) {
            super.onBefore(request);
            setTitle("loading...");
        }

        @Override
        public void onAfter() {
            super.onAfter();
            setTitle("Sample-okHttp");
        }

        @Override
        public void onError(Call call, Exception e) {
            e.printStackTrace();
            mTv.setText("onError:" + e.getMessage());
        }
        //响应的结果太长了,这里截断显示
        @Override
        public void onResponse(String response) {
            mTv.setText("onResponse:" + response.substring(0, 300));
        }

        @Override
        public void inProgress(float progress) {
            Log.e(TAG, "inProgress:" + progress);
            mProgressBar.setProgress((int) (100 * progress));
        }
    }

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

        mTv = (TextView) findViewById(R.id.id_textview);
        mImageView = (ImageView) findViewById(R.id.id_imageview);

        mProgressBar = (ProgressBar) findViewById(R.id.id_progress);
        mProgressBar.setMax(100);

        String url ="http://www.baidu.com";
        getHtml(url);
        String img_url = "http://p0.so.qhimg.com/sdr/720_1080_/t01b59359f15a85528f.jpg";
        getImage(img_url);
    }
    /** * 获得html信息 * @param url */
    public void getHtml(String url) {
        OkHttpUtils
            .get()
            .url(url)
            .addHeader("Accept-Encoding", "utf-8")
            .build()    
            .execute(new MyStringCallback());

    }
    /** * 上传一个json字符串 * @param view */
    public void postString(String url) {
        String json = new Gson().toJson(new User("zhy", "123"));
        OkHttpUtils.postString()
            .url(url)
            .mediaType(MediaType.parse("application/json; charset=utf-8"))
            .content(json)
            .build()
            .execute(new MyStringCallback());

    }


    /** * 登陆 * @param url */
    public void getUser(String url) {
        OkHttpUtils.post()//
                .url(url)//
                .addParams("username", "hyman")//
                .addParams("password", "123")//
                .build()//
                .execute(new UserCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        //mTv.setText("onError:" + e.getMessage());
                    }

                    @Override
                    public void onResponse(User response) {
                        //mTv.setText("onResponse:" + response.username);
                    }
                });
    }

    /** * 下载图片 * @param mImageView */
    public void getImage(String url) {
        OkHttpUtils.get()
                .url(url)
                .tag(this)
                .build()
                .connTimeOut(20000)
                .readTimeOut(20000)
                .writeTimeOut(20000)
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        //
                    }

                    @Override
                    public void onResponse(Bitmap bitmap) {
                        mImageView.setImageBitmap(bitmap);
                    }
                });
    }
    /** * 上传单个文件 * @param url */
    public void uploadFile(String url ) {
        File file = new File(Environment.getExternalStorageDirectory(),"messenger_01.png");
        if (!file.exists()) {
            Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径",Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("username", "张鸿洋");
        params.put("password", "123");

        Map<String, String> headers = new HashMap<>();
        headers.put("APP-Key", "APP-Secret222");
        headers.put("APP-Secret", "APP-Secret111");


        OkHttpUtils.post()//
                .addFile("mFile", "messenger_01.png", file)//
                .url(url)//
                .params(params)//
                .headers(headers)//
                .build()//
                .execute(new MyStringCallback());
    }
    /** * 上传多个文件+params * @param url */
    public void multiFileUpload(String url) {
        File file = new File(Environment.getExternalStorageDirectory(),"messenger_01.png");
        File file2 = new File(Environment.getExternalStorageDirectory(),"test1.txt");

        if (!file.exists()) {
            Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!file2.exists()){
            Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径",Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("username", "张鸿洋");
        params.put("password", "123");

        OkHttpUtils.post()//
                .addFile("mFile", "messenger_01.png", file)//
                .addFile("mFile", "test1.txt", file2)//
                .url(url)
                .params(params)//
                .build()//
                .execute(new MyStringCallback());
    }
/** * 文件下载 * @param view */
    public void downloadFile() {
        String url = "https://github.com/hongyangAndroid/okhttp-utils/blob/master/gson-2.2.1.jar?raw=true";
        String fileDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String fileName = "gson-2.2.1.jar";
        OkHttpUtils//
                .get()//
                .url(url)//
                .build()
                .execute(
                        new FileCallBack(fileDir, fileName) {
                            @Override
                            public void onBefore(Request request) {
                                super.onBefore(request);
                            }

                            @Override
                            public void inProgress(float progress, long total) {
                                mProgressBar.setProgress((int) (100 * progress));
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                                Log.e(TAG, "onError :" + e.getMessage());
                            }

                            @Override
                            public void onResponse(File file) {
                                Log.e(TAG,"onResponse :" + file.getAbsolutePath());
                            }
                        });
    }

    /** * 清除缓存信息 * * @param view */
    public void clearSession(View view) {
        OkHttpUtils.getInstance().getCookieStore().removeAll();
    }

    /** * 取消某个请求 */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }
}

上面的实例中有很多封装好的方法, 可以直接使用。
在实际使用过程中,一些全局性的配置可以在Application中去设置。如https请求,需要加载签名证书。

package com.zhy.sample_okhttp;

import android.app.Application;

import com.zhy.http.okhttp.OkHttpUtils;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okio.Buffer;

/** * 注意:如果https网站为权威机构颁发的证书,不需要以上设置。自签名的证书才需要。 */
public class MyApplication extends Application{
    //12306签名证书
    private String CER_12306 = "-----BEGIN CERTIFICATE-----\n" +
            "MIICmjCCAgOgAwIBAgIIbyZr5/jKH6QwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ04xKTAn\n" +
            "BgNVBAoTIFNpbm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMB4X\n" +
            "DTA5MDUyNTA2NTYwMFoXDTI5MDUyMDA2NTYwMFowRzELMAkGA1UEBhMCQ04xKTAnBgNVBAoTIFNp\n" +
            "bm9yYWlsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRTUkNBMIGfMA0GCSqGSIb3\n" +
            "DQEBAQUAA4GNADCBiQKBgQDMpbNeb34p0GvLkZ6t72/OOba4mX2K/eZRWFfnuk8e5jKDH+9BgCb2\n" +
            "9bSotqPqTbxXWPxIOz8EjyUO3bfR5pQ8ovNTOlks2rS5BdMhoi4sUjCKi5ELiqtyww/XgY5iFqv6\n" +
            "D4Pw9QvOUcdRVSbPWo1DwMmH75It6pk/rARIFHEjWwIDAQABo4GOMIGLMB8GA1UdIwQYMBaAFHle\n" +
            "tne34lKDQ+3HUYhMY4UsAENYMAwGA1UdEwQFMAMBAf8wLgYDVR0fBCcwJTAjoCGgH4YdaHR0cDov\n" +
            "LzE5Mi4xNjguOS4xNDkvY3JsMS5jcmwwCwYDVR0PBAQDAgH+MB0GA1UdDgQWBBR5XrZ3t+JSg0Pt\n" +
            "x1GITGOFLABDWDANBgkqhkiG9w0BAQUFAAOBgQDGrAm2U/of1LbOnG2bnnQtgcVaBXiVJF8LKPaV\n" +
            "23XQ96HU8xfgSZMJS6U00WHAI7zp0q208RSUft9wDq9ee///VOhzR6Tebg9QfyPSohkBrhXQenvQ\n" +
            "og555S+C3eJAAVeNCTeMS3N/M5hzBRJAoffn3qoYdAO1Q8bTguOi+2849A==\n" +
            "-----END CERTIFICATE-----";

    @Override
    public void onCreate(){
        super.onCreate();
        //这里可以设置自签名证书
        //OkHttpUtils.getInstance().setCertificates(new InputStream[] { new Buffer().writeUtf8(CER_12306).inputStream()});


        //设置超时时间
        //OkHttpUtils.getInstance().debug("OkHttpUtils").setConnectTimeout(100000, TimeUnit.MILLISECONDS);

        //使用https,但是默认信任全部证书
       // OkHttpUtils.getInstance().setCertificates();


        //使用https,加载证书。将证书放在assets目录:
// try {
// InputStream is1 = getAssets().open("aaa.cer");
// InputStream is2 = getAssets().open("server.cer");
// OkHttpUtils.getInstance().setCertificates(is1,is2);
// } catch (Exception e) {
// }


        // 使用这种方式,设置多个OkHttpClient参数
        // OkHttpUtils.getInstance(new OkHttpClient.Builder().build());


        //OkHttpClient client = OkHttpUtils.getInstance().getOkHttpClient();

    }
}

参考文章:http://blog.csdn.net/lmj623565791/article/details/49734867

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