温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中OkHttp的作用是什么

发布时间:2021-07-12 10:52:30 来源:亿速云 阅读:396 作者:Leah 栏目:大数据

今天就跟大家聊聊有关Android中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,打开设置界面

Android中OkHttp的作用是什么

点击插件,然后点击Browse repositorie

Android中OkHttp的作用是什么

在弹出的窗体中搜索LayoutCreator,我这里因为已经下载了,所以没有下载按钮,大家可以自己下载,右边有一些对该插件的介绍,可以大概地看一下

Android中OkHttp的作用是什么

下载完毕后,重启一下Android Studio,就可以在这里看到插件了

Android中OkHttp的作用是什么

如何去使用它呢?很简单,先双击选中布局参数

Android中OkHttp的作用是什么

然后点击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);    }}

有些小伙伴可能到这里就走不下去了,查看日志发现

Android中OkHttp的作用是什么

遇到问题不要慌,只有在不断的解决问题的过程中才能成长,这个问题其实是因为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();            }        });

看完上述内容,你们对Android中OkHttp的作用是什么有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI