OkHttp的基本使用

前面讲解了Volley网络请求的使用,这章就来看看OkHttp的使用。
调用的网址如下:

    public static final String GET_HTTP = "http://gank.io/api/day/history";
    public static final String POS_HTTP_WEATHER = "http://api.k780.com:88/";
    public static final String POST_GITHUB_URL = "https://api.github.com/markdown/raw";
  • GET同步使用
    new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url(UrlUtils.GET_HTTP)
                            .method(UrlUtils.GET, null)
                            .build();

                    Response response = mOkHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getSyn->", response.body().string()));
                    } else {
                        Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getSyn->", "请求失败"));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
  • GET异步的使用
        Request request = new Request.Builder()
                .url(UrlUtils.GET_HTTP)
                .method(UrlUtils.GET, null)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    Log.e("LHC_OKHTTP", "请求成功");
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getAsyn->", response.body().string()));
                } else {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "getAsyn->", response.networkResponse().toString()));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("请求成功");
                    }
                });
            }
        });
  • POST的同步使用
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RequestBody body = new FormBody.Builder().add("app", "weather.future")
                            .add("weaid", "1").add("appkey", "10003").add("sign",
                                    "b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
                            .build();
                    Request request = new Request.Builder()
                            .url(UrlUtils.POS_HTTP_WEATHER)
                            .post(body)
                            .build();
                    Response response = mOkHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postSyn->", response.body().string()));
                    } else {
                        Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postSyn->", "请求失败"));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
  • POST异步使用
        RequestBody body = new FormBody.Builder().add("app", "weather.future")
                .add("weaid", "1").add("appkey", "10003").add("sign",
                        "b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
                .build();
        Request request = new Request.Builder()
                .url(UrlUtils.POS_HTTP_WEATHER)
                .post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "postAsyn():请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsyn->", response.body().string()));
                } else {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsyn->", response.networkResponse().toString()));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("请求成功");
                    }
                });
            }
        });
    }
  • POST异步传String
        RequestBody body = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "api.github.com/markdown/raw");
        Request request = new Request.Builder()
                .url(UrlUtils.POST_GITHUB_URL)
                .post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "postAsynString():请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynString->", response.body().string()));
                } else {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynString->", response.networkResponse().toString()));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("请求成功");
                    }
                });
            }
        });
  • POST异步传文件
        File file = new File(Environment.getExternalStorageDirectory()+"/test.txt");//传递的文件地址
        RequestBody body = RequestBody.create(MediaType.parse("text/x-markdown;charset=utf-8"), file);
        Request request = new Request.Builder()
                .url(UrlUtils.POST_GITHUB_URL)
                .post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "postAsynFile():请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynFile->", response.body().string()));
                } else {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynFile->", response.networkResponse().toString()));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("请求成功");
                    }
                });
            }
        });
  • POST异步传流
        RequestBody body = new RequestBody() {
            @Nullable
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown;charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("Number:\n");
                for (int i = 2; i <= 997; i++) {
                    sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
                }
            }
        };

        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(body)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "postAsynStream():请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynStream->", response.body().string()));
                } else {
                    Log.e("LHC_OKHTTP", String.format("%svalue:%s", "postAsynStream->", response.networkResponse().toString()));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("请求成功");
                    }
                });
            }
        });
    }

    private String factor(int n) {
        for (int i = 2; i < n; i++) {
            int x = n / i;
            if (x * i == n) return factor(x) + " × " + i;
        }
        return Integer.toString(n);
    }
  • GET下载图片
        Request request = new Request.Builder()
                .url(UrlUtils.URL_IMAGE)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "downLoadFile():请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                if (response != null && response.body() != null) {
                    ThreadUtil.getInstance().getExecutorService().execute(new Runnable() {//线程池生成新线程
                        @Override
                        public void run() {
                            writeFileToDisk(response);
                        }
                    });
                }
            }
        });

    private void writeFileToDisk(Response response) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            byte[] buff = new byte[2048];
            is = response.body().byteStream();
            File filePath = new File(FILE_DIR);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            final File file = new File(filePath, FILE_NAME);
            fos = new FileOutputStream(file);

            int len = 0;
            while ((len = is.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Glide.with(OkHttpSimpleUseActivity.this).load(file.getAbsoluteFile()).into(ivShow);
                }
            });
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • POST上传多个文件
        List<File> files = new ArrayList<>();
        files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "crop_image.jpg"));
        files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "temp.png"));

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        for (File file : files) {
            String filePath = file.getAbsolutePath();
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
            builder.addFormDataPart("files", fileName, MultipartBody.create(MediaType.parse("application/octet-stream"), file));//这里的参数"files"是需要传递给服务器的参数名称
        }

        Request request = new Request.Builder()
                .url(UrlUtils.URL_UPLOAD)
                .post(builder.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "upLoadFile():请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Log.e("LHC_OKHTTP", "body:" + response.body().string());
                ToastUtils.showShort("上传成功");
            }
        });
  • OkHttp简单的二次封装
public class OkHttpHelper {
    private static OkHttpHelper okHttpHelper = null;
    private static OkHttpClient okHttpClient = null;

    public static OkHttpHelper getInstance() {
        if (okHttpHelper == null) {
            synchronized (OkHttpHelper.class) {
                if (okHttpHelper == null) {
                    okHttpHelper = new OkHttpHelper();
                }
            }
        }
        return okHttpHelper;
    }

    private static Handler mHandler = null;

    synchronized Handler getHandler() {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        return mHandler;
    }

    private synchronized OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            long cacheSize = 10 * 1024 * 1024;
            String cachePath = Environment.getDownloadCacheDirectory() + File.separator;
            File cacheFile = new File(cachePath, "OkHttp_Cache");
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                if (!cacheFile.exists() && !cacheFile.isDirectory()) {
                    cacheFile.mkdir();
                }
            }
            Cache cache = new Cache(cacheFile, cacheSize);

            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.e("OkHttpLog", "" + message);
                }
            });
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .cache(cache)//设置缓存
                    .addInterceptor(httpLoggingInterceptor)//设置输出日志拦截器
                    .addNetworkInterceptor(createHttpInterceptor())//设置网络拦截器
                    .build();
        }

        return okHttpClient;
    }

    /**
     * 异步GET
     *
     * @param url      网址
     * @param callback 回调
     */
    public void doGet(String url, Callback callback) {
        OkHttpClient okHttpClient = getOkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 异步POST
     *
     * @param url      网址
     * @param params   参数
     * @param callback 回调
     */
    public void doPost(String url, Map<String, String> params, Callback callback) {
        OkHttpClient postClient = getOkHttpClient();
        FormBody.Builder body = new FormBody.Builder();
        for (String s : params.keySet()) {
            body.add(s, params.get(s));
        }
        Request request = new Request.Builder().url(url).post(body.build()).build();
        postClient.newCall(request).enqueue(callback);
    }

    public void doPostJson(String url, String jsonParams, Callback callback) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(body).build();
        getOkHttpClient().newCall(request).enqueue(callback);
    }

    /**
     * 上传文件
     *
     * @param url      上传文件地址
     * @param files    文件 上传文件列表
     * @param callback 回调
     */
    public void uploadFileNew(String url, List<File> files, Callback callback) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        for (File file : files) {
            String filePath = file.getAbsolutePath();
            String fileName = filePath.substring(filePath.lastIndexOf("/"));
            builder.addFormDataPart("files", fileName, MultipartBody.create(MediaType.parse("application/octet-stream"), file));
        }

        Request request = new Request.Builder().url(url).post(builder.build()).build();
        getOkHttpClient().newCall(request).enqueue(callback);
    }

    /**
     * 下载图片
     *
     * @param url      下载网址
     * @param callback 回调
     */
    public void downLoadFile(String url, Callback callback) {
        Request request = new Request.Builder().url(url).build();
        getOkHttpClient().newCall(request).enqueue(callback);
    }

    private static Interceptor createHttpInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                int maxAge = 60 * 60;//有网络时设置缓存超时时间为1小时
                int maxStale = 24 * 60 * 60;//没有网络时设置缓存超时时间为24小时

                if (NetWorkUtils.isNetworkAvailable(StudyApplication.getContext())) {
                    //有网的情况下,只从网络上获取数据
                    request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
                } else {
                    //没有网的情况下,只从缓存中获取数据
                    request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                }

                Response response = chain.proceed(request);
                if (NetWorkUtils.isNetworkAvailable(StudyApplication.getContext())) {
                    response = response.newBuilder()
                            .removeHeader("Pragma")
                            .header("Cache_Control", "public, max-age=" + maxAge)
                            .build();
                } else {
                    response = response.newBuilder()
                            .removeHeader("Pragma")
                            .header("Cache_Control", "public, only-if-cache, max-stale=" + maxStale)
                            .build();
                }
                return response;
            }
        };
    }
}
  • 下载文件回调封装
public abstract class DownFileCallback implements Callback{
    private String FILE_DIR = Environment.getExternalStorageDirectory() + File.separator+"downImage";
    private String FILE_NAME = "ok_"+System.currentTimeMillis()+".jpg";

    private Handler mHandler = OkHttpHelper.getInstance().getHandler();

    public abstract void onUI(String path);
    public abstract void onFailed(Call call, IOException e);

    @Override
    public void onFailure(final Call call, final IOException e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                onFailed(call, e);
            }
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response != null && response.body() !=  null){
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                byte[] buff = new byte[2048];
                is = response.body().byteStream();
                File filePath = new File(FILE_DIR);
                if (!filePath.mkdirs()){
                    filePath.createNewFile();
                }
                final File file = new File(filePath, FILE_NAME);
                fos = new FileOutputStream(file);
                int len = 0;
                while ((len = is.read(buff)) != -1){
                    fos.write(buff, 0 , len);
                }

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onUI(file.getAbsolutePath());
                    }
                });

                fos.flush();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if (is != null){
                    is.close();
                }
                if (fos != null){
                    fos.close();
                }
            }

        }
    }
}
  • GSON解析回调封装
public abstract class GsonObjectCallback<T> implements Callback {
    private Handler mHandler = OkHttpHelper.getInstance().getHandler();

    public abstract void onUI(T t);
    public abstract void onFailed(Call call, IOException e);

    @Override
    public void onFailure(final Call call, final IOException e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                onFailed(call, e);
            }
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response != null && response.body() != null) {
            String result = response.body().string();

            Class clz = this.getClass();
            ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();
            Type[] types = type.getActualTypeArguments();
            Class<T> cls  = (Class<T>) types[0];
            Gson gson = new Gson();
            final T t = gson.fromJson(result, cls);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    onUI(t);
                }
            });

        }
    }
}
  • 封装GET异步 下载图片
        OkHttpHelper.getInstance().downLoadFile(UrlUtils.URL_IMAGE, new DownFileCallback() {
            @Override
            public void onUI(String path) {
                Glide.with(OkHttpFZUseActivity.this).load(new File(path)).into(ivShow);
            }

            @Override
            public void onFailed(Call call, IOException e) {
                Log.e("LHC_OKHTTP", "下载失败");
            }
        });
  • 封装POST异步 上传图片
                List<File> files = new ArrayList<>();
                files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "crop_image.jpg"));
                files.add(new File(Environment.getExternalStorageDirectory() + File.separator + "temp.png"));
                OkHttpHelper.getInstance().uploadFileNew(UrlUtils.URL_UPLOAD, files, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("LHC_OKHTTP", "上传失败");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        Log.e("LHC_OKHTTP", "body:" + response.body().string());
                        ToastUtils.showShort("上传成功");
                    }
                });
  • 封装GET异步
                OkHttpHelper.getInstance().doGet(UrlUtils.GET_HTTP, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("LHC_OKHTTP", "请求失败");
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShort("请求成功");
                            }
                        });
                    }
                });
  • 封装POST异步
                Map<String, String> params = new HashMap<>();
                params.put("app", "weather.future");
                params.put("weaid", "1");
                params.put("appkey", "10003");
                params.put("sign", "b59bc3ef6191eb9f747dd4e83c99f2a4");
                params.put("format", "json");
                OkHttpHelper.getInstance().doPost(UrlUtils.POS_HTTP_WEATHER, params, new GsonObjectCallback<Weathers>() {
                    @Override
                    public void onUI(Weathers weathers) {
                        ToastUtils.showShort(weathers.getResult().get(0).getCitynm());
                    }

                    @Override
                    public void onFailed(Call call, IOException e) {
                        ToastUtils.showShort("请求失败");
                    }
                });
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容