当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发之OkHttp介绍

Android开发之OkHttp介绍

2019年08月26日  | 移动技术网移动技术  | 我要评论

要论时下最火的网络请求框架,当属okhttp了。自从android4.4开始,google已经开始将源码中的httpurlconnection替换为okhttp,而在android6.0之后的sdk中google更是移除了对于httpclient的支持,而市面上流行的retrofit同样是使用okhttp进行再次封装而来的。由此可见okhttp有多强大了。

下面来简单介绍一下okhttp:
http是现代应用常用的一种交换数据和媒体的网络方式,高效地使用http能让资源加载更快,节省带宽。okhttp是一个高效的http客户端,它有以下默认特性:

支持http/2,允许所有同一个主机地址的请求共享同一个socket连接
连接池减少请求延时
透明的gzip压缩减少响应数据的大小
缓存响应内容,避免一些完全重复的请求
当网络出现问题的时候okhttp依然坚守自己的职责,它会自动恢复一般的连接问题,如果你的服务有多个ip地址,当第一个ip请求失败时,okhttp会交替尝试你配置的其他ip,okhttp使用现代tls技术(sni, alpn)初始化新的连接,当握手失败时会回退到tls 1.0。
废话不多数,马上进入正题。
要想使用okhttp,得先配置gradle环境,也可以下载jar包然后添加到自己的项目
下面来具体使用一下okhttp
首先绘制布局,这里简单绘制一下,布局里添加了一个按钮和一个可以滚动的文本框

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".mainactivity">

   <button
       android:layout_width="wrap_content"
       android:id="@+id/btn_getdata"
       android:text="请求数据"
       android:textsize="25sp"
       android:layout_gravity="center"
       android:layout_height="wrap_content" />
    <scrollview
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <textview
            android:layout_width="match_parent"
            android:id="@+id/tv_result"
            android:layout_height="wrap_content" />
    </scrollview>

</linearlayout>

然后回到mainactivity中,寻找控件并设置相关属性,这里给大家推荐一个小工具(layoutcreator),不用再去重复编写findviewbyid(),解放你们的双手。
首先点击file,打开设置界面在这里插入图片描述

点击插件,然后点击browse repositorie
在这里插入图片描述
在弹出的窗体中搜索layoutcreator,我这里因为已经下载了,所以没有下载按钮,大家可以自己下载,右边有一些对该插件的介绍,可以大概地看一下
在这里插入图片描述

下载完毕后,重启一下android studio,就可以在这里看到插件了
在这里插入图片描述
如何去使用它呢?很简单,先双击选中布局参数
在这里插入图片描述
然后点击code,继续点击layoutcreator,代码就自动生成了,是不是很方便呢?前提是你的控件必须有id,没有id值是无法自动生成代码的。
说了这么多,怎么感觉跑题了,请原谅我迫切想与大家分享插件的心,回归正题。
网络请求无非就是get请求和post请求,下面具体介绍okhttp是如何进行get请求和post请求的

get请求

okhttpclient client = new okhttpclient();
string run(string url) throws ioexception {
    request request = new request.builder().url(url).build();
    response response = client.newcall(request).execute();
    if (response.issuccessful()) {
        return response.body().string();
    } else {
        throw new ioexception("unexpected code " + response);
    }
}

有些小伙伴可能到这里就走不下去了,查看日志发现
在这里插入图片描述
遇到问题不要慌,只有在不断的解决问题的过程中才能成长,这个问题其实是因为okhttp的库依赖于okio.jar这个jar包,可以去github上下载:
继续说get请求,使用execute()方法发送请求后,就会进入阻塞状态,直到收到响应
当然,okhttp也给我们封装了异步请求方法,异步方法是在回调中处理响应的

okhttpclient client = new okhttpclient.builder().readtimeout(5, timeunit.seconds).build();
        request request = new request.builder().url("http://www.baidu.com")
                .get().build();
        call call = client.newcall(request);
        call.enqueue(new callback() {
            @override
            public void onfailure(call call, ioexception e) {
                system.out.println("fail");
            }

            @override
            public void onresponse(call call, response response) throws ioexception {

                system.out.println(response.body().string());

            }
        });

post方法进行同步请求

string okpost(string url, string json) throws ioexception {
    mediatype json = mediatype.parse("application/json; charset=utf-8");
    requestbody body = requestbody.create(json, json);
    request request = new request.builder()
            .url(url)
            .post(body)
            .build();
    response response = client.newcall(request).execute();
    return response.body().string();
}

post方法异步请求

okhttpclient okhttpclient = new okhttpclient();
        //form表单格式的参数传递
        formbody formbody = new formbody
                .builder()
                .add("username","androidxx.cn")//设置参数名称和参数值
                .build();
        request request = new request
                .builder()
                .post(formbody)//post请求的参数传递
                .url(config.localhost_post_url)
                .build();
        okhttpclient.newcall(request).enqueue(new callback() {
            @override
            public void onfailure(call call, ioexception e) {}

            @override
            public void onresponse(call call, response response) throws ioexception {
                //此方法运行在子线程中,不能在此方法中进行ui操作。
                string result = response.body().string();
                log.d("androixx.cn", result);
                response.body().close();
            }
        });

讲到这里,相信大家对okhttp有了一定的了解了吧,使用方法也非常简单,感谢大家的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网