Android 使用OkHttp

2024-09-05 09:18
文章标签 android 使用 okhttp

本文主要是介绍Android 使用OkHttp,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

为什么需要一个HTTP库

Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。

关于HttpURLConnection和HttpClient的选择>>官方博客

尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。

OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。

入门

官方资料

官方介绍

github源码

使用范围

OkHttp支持Android 2.3及其以上版本。 对于Java, JDK1.7以上。

jar包准备

官方介绍页面有链接位置。这里把下载链接也写在下面。

OkHttp

Okio

基本使用

HTTP GET

<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;">OkHttpClient client = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();String run(String url) throws IOException {
<span class="indent">  </span>Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder().url(url).build();
<span class="indent">  </span>Response response = client.newCall(request).execute();
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">if</span> (response.isSuccessful()) {
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> response.body().<span class="keyword" style="font-weight: bold;">string</span>();
<span class="indent">  </span>} <span class="keyword" style="font-weight: bold;">else</span> {
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response);
<span class="indent">  </span>}
}</code>

Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。

Response类:
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> boolean isSuccessful()
Returns <span class="keyword" style="font-weight: bold;">true</span> <span class="keyword" style="font-weight: bold;">if</span> the code <span class="keyword" style="font-weight: bold;">is</span> <span class="keyword" style="font-weight: bold;">in</span> [<span class="number" style="color: rgb(0, 153, 153);">200.</span><span class="number" style="color: rgb(0, 153, 153);">.300</span>), which means the request was successfully received, understood, and accepted.</code>
response.body()返回ResponseBody类

可以方便的获取string

<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> final String <span class="keyword" style="font-weight: bold;">string</span>() throws IOException
Returns the response <span class="keyword" style="font-weight: bold;">as</span> a <span class="keyword" style="font-weight: bold;">string</span> decoded with the charset of the Content-Type header. If that header <span class="keyword" style="font-weight: bold;">is</span> either absent or lacks a charset, <span class="keyword" style="font-weight: bold;">this</span> will attempt to decode the response body <span class="keyword" style="font-weight: bold;">as</span> UTF-<span class="number" style="color: rgb(0, 153, 153);">8.</span>
Throws:
IOException</code>

当然也能获取到流的形式:

<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">final</span> InputStream byteStream()</code>

HTTP POST

POST提交Json数据
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">final</span> MediaType JSON = MediaType.parse(<span class="string" style="color: rgb(221, 17, 68);">"application/json; charset=utf-8"</span>);
OkHttpClient client = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();
String post(String url, String json) <span class="keyword" style="font-weight: bold;">throws</span> IOException {RequestBody body = RequestBody.create(JSON, json);Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder()
<span class="indent">  </span>  .url(url)
<span class="indent">  </span>  .post(body)
<span class="indent">  </span>  .build();Response response = client.newCall(request).execute();
<span class="indent">  </span>f (response.isSuccessful()) {
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> response.body().string();
<span class="indent">  </span>} <span class="keyword" style="font-weight: bold;">else</span> {
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response);
<span class="indent">  </span>}
}</code>

使用Request的post方法来提交请求体RequestBody

POST提交键值对

很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。

<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;">OkHttpClient client = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();
String post(String url, String json) throws IOException {RequestBody formBody = <span class="keyword" style="font-weight: bold;">new</span> FormEncodingBuilder()
<span class="indent">  </span>.add(<span class="string" style="color: rgb(221, 17, 68);">"platform"</span>, <span class="string" style="color: rgb(221, 17, 68);">"android"</span>)
<span class="indent">  </span>.add(<span class="string" style="color: rgb(221, 17, 68);">"name"</span>, <span class="string" style="color: rgb(221, 17, 68);">"bug"</span>)
<span class="indent">  </span>.add(<span class="string" style="color: rgb(221, 17, 68);">"subject"</span>, <span class="string" style="color: rgb(221, 17, 68);">"XXXXXXXXXXXXXXX"</span>)
<span class="indent">  </span>.build();Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder().url(url).post(body).build();Response response = client.newCall(request).execute();
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">if</span> (response.isSuccessful()) {
<span class="indent">  </span>    <span class="keyword" style="font-weight: bold;">return</span> response.body().<span class="keyword" style="font-weight: bold;">string</span>();
<span class="indent">  </span>} <span class="keyword" style="font-weight: bold;">else</span> {
<span class="indent">  </span>    <span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response);
<span class="indent">  </span>}
}</code>

总结

通过上面的例子我们可以发现,OkHttp在很多时候使用都是很方便的,而且很多代码也有重复,因此特地整理了下面的工具类。 注意:

  • OkHttp官方文档并不建议我们创建多个OkHttpClient,因此全局使用一个。 如果有需要,可以使用clone方法,再进行自定义。这点在后面的高级教程里会提到。
  • enqueue为OkHttp提供的异步方法,入门教程中并没有提到,后面的高级教程里会有解释。
<code style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; border: 0px; display: block; overflow-y: auto;"><span class="keyword" style="font-weight: bold;">import</span> java.io.IOException;
<span class="keyword" style="font-weight: bold;">import</span> java.util.List;
<span class="keyword" style="font-weight: bold;">import</span> java.util.concurrent.TimeUnit;
<span class="keyword" style="font-weight: bold;">import</span> org.apache.http.client.utils.URLEncodedUtils;
<span class="keyword" style="font-weight: bold;">import</span> org.apache.http.message.BasicNameValuePair;
<span class="keyword" style="font-weight: bold;">import</span> cn.wiz.sdk.constant.WizConstant;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.Callback;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.OkHttpClient;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.Request;
<span class="keyword" style="font-weight: bold;">import</span> com.squareup.okhttp.Response; <span class="keyword" style="font-weight: bold;">public</span> <span class="class" style="color: rgb(68, 85, 136); font-weight: bold;"><span class="keyword" style="color: rgb(51, 51, 51);">class</span> <span class="title">OkHttpUtil</span> {</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">private</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">final</span> OkHttpClient mOkHttpClient = <span class="keyword" style="font-weight: bold;">new</span> OkHttpClient();
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">static</span>{
<span class="indent">  </span><span class="indent">  </span>mOkHttpClient.setConnectTimeout(<span class="number" style="color: rgb(0, 153, 153);">30</span>, TimeUnit.SECONDS);
<span class="indent">  </span>}
<span class="indent">  </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent">  </span> * 该不会开启异步线程。
<span class="indent">  </span> * <span class="javadoctag">@param</span> request
<span class="indent">  </span> * <span class="javadoctag">@return</span>
<span class="indent">  </span> * <span class="javadoctag">@throws</span> IOException
<span class="indent">  </span> */</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> Response execute(Request request) <span class="keyword" style="font-weight: bold;">throws</span> IOException{
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> mOkHttpClient.newCall(request).execute();
<span class="indent">  </span>}
<span class="indent">  </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent">  </span> * 开启异步线程访问网络
<span class="indent">  </span> * <span class="javadoctag">@param</span> request
<span class="indent">  </span> * <span class="javadoctag">@param</span> responseCallback
<span class="indent">  </span> */</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">void</span> enqueue(Request request, Callback responseCallback){
<span class="indent">  </span><span class="indent">  </span>mOkHttpClient.newCall(request).enqueue(responseCallback);
<span class="indent">  </span>}
<span class="indent">  </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent">  </span> * 开启异步线程访问网络, 且不在意返回结果(实现空callback)
<span class="indent">  </span> * <span class="javadoctag">@param</span> request
<span class="indent">  </span> */</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">void</span> enqueue(Request request){
<span class="indent">  </span><span class="indent">  </span>mOkHttpClient.newCall(request).enqueue(<span class="keyword" style="font-weight: bold;">new</span> Callback() {
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="annotation">@Override</span>
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">void</span> onResponse(Response arg0) <span class="keyword" style="font-weight: bold;">throws</span> IOException {
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>}
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="annotation">@Override</span>
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">void</span> onFailure(Request arg0, IOException arg1) {
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>}
<span class="indent">  </span><span class="indent">  </span>});
<span class="indent">  </span>}
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String getStringFromServer(String url) <span class="keyword" style="font-weight: bold;">throws</span> IOException{
<span class="indent">  </span><span class="indent">  </span>Request request = <span class="keyword" style="font-weight: bold;">new</span> Request.Builder().url(url).build();
<span class="indent">  </span><span class="indent">  </span>Response response = execute(request);
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">if</span> (response.isSuccessful()) {
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span>String responseUrl = response.body().string();
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> responseUrl;
<span class="indent">  </span><span class="indent">  </span>} <span class="keyword" style="font-weight: bold;">else</span> {
<span class="indent">  </span><span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">throw</span> <span class="keyword" style="font-weight: bold;">new</span> IOException(<span class="string" style="color: rgb(221, 17, 68);">"Unexpected code "</span> + response);
<span class="indent">  </span><span class="indent">  </span>}
<span class="indent">  </span>}
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">private</span> <span class="keyword" style="font-weight: bold;">static</span> <span class="keyword" style="font-weight: bold;">final</span> String CHARSET_NAME = <span class="string" style="color: rgb(221, 17, 68);">"UTF-8"</span>;
<span class="indent">  </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent">  </span> * 这里使用了HttpClinet的API。只是为了方便
<span class="indent">  </span> * <span class="javadoctag">@param</span> params
<span class="indent">  </span> * <span class="javadoctag">@return</span>
<span class="indent">  </span> */</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String formatParams(List<BasicNameValuePair> params){
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> URLEncodedUtils.format(params, CHARSET_NAME);
<span class="indent">  </span>}
<span class="indent">  </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent">  </span> * 为HttpGet 的 url 方便的添加多个name value 参数。
<span class="indent">  </span> * <span class="javadoctag">@param</span> url
<span class="indent">  </span> * <span class="javadoctag">@param</span> params
<span class="indent">  </span> * <span class="javadoctag">@return</span>
<span class="indent">  </span> */</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String attachHttpGetParams(String url, List<BasicNameValuePair> params){
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> url + <span class="string" style="color: rgb(221, 17, 68);">"?"</span> + formatParams(params);
<span class="indent">  </span>}
<span class="indent">  </span><span class="javadoc" style="color: rgb(153, 153, 136); font-style: italic;">/**
<span class="indent">  </span> * 为HttpGet 的 url 方便的添加1个name value 参数。
<span class="indent">  </span> * <span class="javadoctag">@param</span> url
<span class="indent">  </span> * <span class="javadoctag">@param</span> name
<span class="indent">  </span> * <span class="javadoctag">@param</span> value
<span class="indent">  </span> * <span class="javadoctag">@return</span>
<span class="indent">  </span> */</span>
<span class="indent">  </span><span class="keyword" style="font-weight: bold;">public</span> <span class="keyword" style="font-weight: bold;">static</span> String attachHttpGetParam(String url, String name, String value){
<span class="indent">  </span><span class="indent">  </span><span class="keyword" style="font-weight: bold;">return</span> url + <span class="string" style="color: rgb(221, 17, 68);">"?"</span> + name + <span class="string" style="color: rgb(221, 17, 68);">"="</span> + value;
<span class="indent">  </span>}
}</code>

高级

高级属性其实用的不多,这里主要是对OkHttp github官方教程进行了翻译。

请看我的另一篇博客: OkHttp使用进阶 译自OkHttp Github官方教程

这篇关于Android 使用OkHttp的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138544

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的