Okhttp3-基本用法

作者: 秦子帅 | 来源:发表于2019-08-15 15:33 被阅读0次

前言

Okhttp官网
Okhttp-Github

android网络框架之OKhttp一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso)

用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient)

官网的解释如下:


基本用法

1.集成
1.1.依赖
   implementation 'com.squareup.okhttp3:okhttp:3.11.0'

可以去Okhttp-Github 查看并依赖最新的版本。

1.2权限

添加网络权限

  <uses-permission android:name="android.permission.INTERNET" />
2.使用
2.1 同步GET请求
  • 构建OkHttpClient对象
  • 构建Request对象
  • 构建Call对象并通过execute()方法来执行同步Get请求
 //同步请求
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request=new Request.Builder()
                .url("https://www.wanandroid.com/navi/json")
                .get()
                .build();
        final Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            Log.e("同步结果----   ",response.body().string()+"");

        } catch (IOException e) {

            e.printStackTrace();

        }

运行后发现报错:

 android.os.NetworkOnMainThreadException

在Android4.0以后,会发现,只要是写在主线程(就是Activity)中的HTTP请求,运行时都会报错,这是因为Android在4.0以后为了防止应用的ANR(Aplication Not Response)异常。解决方法就是在子线程中运行:

        //同步请求
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request=new Request.Builder()
                .url("https://www.wanandroid.com/navi/json")
                .get()
                .build();
        final Call call = okHttpClient.newCall(request);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    Log.e("同步结果----   ",response.body().string()+"");

                } catch (IOException e) {

                    e.printStackTrace();

                }
            }
        }).start();
2.2 异步GET请求
   //异步请求
        OkHttpClient okHttpClient=new OkHttpClient();
        final Request request=new Request.Builder()
                .url("https://www.wanandroid.com/navi/json")
                .get()
                .build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("okhttp_error",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson=new Gson();

                Log.d("okhttp_success",response.body().string());
            }
        });
2.3 POST请求

POST请求支持提交文件,流,string,表单等等 。这里拿POST表单请求作为请求示例:

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("username", "qinzishuai")
                .add("password", "111111")
                .build();
        Request request = new Request.Builder()
                .url("https://www.wanandroid.com/user/login")
                .post(requestBody)
                .build();   

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("okhttp", "onFailure: " + e.getMessage());
            }

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

                Log.d("okhttp", "onResponse: " + response.body().string());
            }
        });

相关文章

  • OkHttp3-基本用法

    转载请注明出处 http://www.jianshu.com/p/7919cd2685d3 (作者:韩栋)本文为译...

  • Okhttp3-基本用法

    前言 Okhttp官网Okhttp-Github android网络框架之OKhttp一个处理网络请求的开源项目,...

  • 定时器

    setTimeout和clearTimeout基本用法 setInterval和clearInterval基本用法...

  • 2019-11-16

    E战到底DAY14 SUMIF和SUMIFS函数 一.基本用法 SUMIF基本用法 SUMIFS基本用法 SUMI...

  • 文章收集

    1、OkHttp3-拦截器(Interceptor)http://www.jianshu.com/p/fc4d43...

  • 11 - 动态数据绑定实现原理

    一、defineProperty 基本用法 1、基本写法: 2、参数 3、descriptor 参数的基本用法 1...

  • as 基本用法

    插件安装 plugin auto import 相当于 eclipse ctrl+o 或者as alt+enter...

  • 基本用法

    Installation 安装 npm install vue vue-server-renderer --sav...

  • 基本用法

    html css js

  • 基本用法

    本地与远程:push 命令会把本地仓库推送到远程仓库(比如gitbub,码云)在push之前要与某个远程仓库建立连...

网友评论

    本文标题:Okhttp3-基本用法

    本文链接:https://www.haomeiwen.com/subject/syvgjctx.html