OkHttp库简介

布满荆棘的人生 2022-05-24 23:16 245阅读 0赞

一直以来,Java并没有什么比较好用的HTTP库,JDK自带的HTTP类又非常旧,难以使用。今天我发现了一个使用比较广泛的OkHttp库,它在安卓和Java领域都有使用,在Github上的星数有两万多,所以我们可以放心的使用。

安装

先来看看如何安装OkHttp。最简单的方法就是直接下载jar包,然后放到项目类路径中。官网上就有下载链接,直接下载即可使用。当然这里要说的是如何使用Maven和Gradle来下载它,目前最新的OkHttp版本是3.10。使用Maven的话,复制下面的到pom.xml中。

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>3.10.0</version>
  5. </dependency>

使用Gradle的话,复制下面的代码。

  1. compile 'com.squareup.okhttp3:okhttp:3.10.0'

使用

获取网页内容

首先需要构造一个OkHttpClient对象,然后在构造一个Request对象,然后获取Response对象就可以了。Response对象中包含网页的各种信息,用Response.body方法即可获取网页内容。下面是获取百度首页代码的例子。

  1. public static void getWebContent() throws IOException {
  2. OkHttpClient client = new OkHttpClient();
  3. String baidu_url = "https://www.baidu.com";
  4. Request request = new Request.Builder()
  5. .url(baidu_url)
  6. .build();
  7. try (Response response = client.newCall(request).execute()) {
  8. Headers headers = response.headers();
  9. String body = response.body().string();
  10. System.out.println("--------headers--------\n" + headers);
  11. System.out.println("--------body--------\n" + body);
  12. }

代码执行结果如下。

  1. --------headers--------
  2. Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
  3. Connection: Keep-Alive
  4. Content-Type: text/html
  5. Date: Thu, 03 May 2018 16:34:29 GMT
  6. Last-Modified: Mon, 23 Jan 2017 13:23:50 GMT
  7. Pragma: no-cache
  8. Server: bfe/1.0.8.18
  9. Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
  10. Transfer-Encoding: chunked
  11. --------body--------
  12. <!DOCTYPE html>
  13. <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>'); </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

GET方式发送信息

我找了找,OkHttp库好像没有GET发送信息的方式,我想了想GET发送信息就是直接把信息作为路径参数发送,所以完全可以自己构造。这大概就是OkHttp不提供该方法的原因吧。

POST方式发送信息

这里直接引用了官方的代码实例,可以参考原网页。简单说,就是先构造一个RequestBody对象,然后将其传递给Request对象的post方法。这里这个例子发送的是JSON数据,如果我们改一下MediaType就可以发送其他类型的数据了。

  1. public class PostExample {
  2. public static final MediaType JSON
  3. = MediaType.parse("application/json; charset=utf-8");
  4. OkHttpClient client = new OkHttpClient();
  5. String post(String url, String json) throws IOException {
  6. RequestBody body = RequestBody.create(JSON, json);
  7. Request request = new Request.Builder()
  8. .url(url)
  9. .post(body)
  10. .build();
  11. try (Response response = client.newCall(request).execute()) {
  12. return response.body().string();
  13. }
  14. }
  15. String bowlingJson(String player1, String player2) {
  16. return "{'winCondition':'HIGH_SCORE',"
  17. + "'name':'Bowling',"
  18. + "'round':4,"
  19. + "'lastSaved':1367702411696,"
  20. + "'dateStarted':1367702378785,"
  21. + "'players':["
  22. + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
  23. + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
  24. + "]}";
  25. }
  26. public static void main(String[] args) throws IOException {
  27. PostExample example = new PostExample();
  28. String json = example.bowlingJson("Jesse", "Jake");
  29. String response = example.post("http://www.roundsapp.com/post", json);
  30. System.out.println(response);
  31. }
  32. }

POST发送表单

作为一个常见需求,我写了一个例子作为参考。OkHttp库也对此作了特别处理,我们可以利用FormBody.Builder非常方便的构造表单专用的RequestBody。当然,用上面的方法也可以,注意一下表单的媒体类型是application/x-www-form-urlencoded即可。

  1. static void postForm() throws IOException {
  2. OkHttpClient client = new OkHttpClient();
  3. String url = "http://httpbin.org/post";
  4. RequestBody requestBody = new FormBody.Builder().add("name", "yitian")
  5. .add("age", "25")
  6. .build();
  7. // 等价方法
  8. // requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf8"),
  9. // "name=yitian&age=25");
  10. Request request = new Request.Builder()
  11. .url(url)
  12. .post(requestBody)
  13. .build();
  14. String body = client.newCall(request).execute().body().string();
  15. System.out.println("---------post form---------");
  16. System.out.println(body);
  17. }

异步获取信息

有时候需要请求的数据比较大,使用前面的同步方式会造成卡顿,这时候就需要异步方式了。异步方式其实也很简单,只需要改为使用OkHttpClient的enquene方法,该方法接受一个Callback对象,作为异步操作的回调。Callback接口有两个方法,一个是成功之后的操作,一个是失败之后的操作。下面是异步获取网页内容的例子,大家一看就会明白。

  1. static void getWebContentAsync() throws IOException {
  2. OkHttpClient client = new OkHttpClient();
  3. String baidu_url = "https://www.baidu.com";
  4. Request request = new Request.Builder()
  5. .url(baidu_url)
  6. .build();
  7. client.newCall(request).enqueue(new Callback() {
  8. @Override
  9. public void onFailure(Call call, IOException e) {
  10. e.printStackTrace();
  11. }
  12. @Override
  13. public void onResponse(Call call, Response response) throws IOException {
  14. Headers headers = response.headers();
  15. String body = response.body().string();
  16. System.out.println("--------headers--------\n" + headers);
  17. System.out.println("--------body--------\n" + body);
  18. }
  19. });
  20. }

异步下载文件

另外一个常见需求就是下载文件,用OkHttp也可以非常方便的做到。当然由于网络上下载文件一般用时比较长,所以这个过程一般情况下都要做成异步的。下面的例子是从百度图片库中下载一张图片,保存图片使用了Java 8中NIO的方法,相对于以前使用嵌套的文件流相比优雅了许多。下载文件这个过程用时可能比较慢,所以这个例子需要稍微多一些时间。一开始我尝试下载外网上的图片,结果好几分钟才下载完,然后我一看文件还出错了。所以最后还是改成百度上的图片。

  1. static void downloadImage() {
  2. String img_url = "http://imgsrc.baidu.com/forum/pic/item/887018fa828ba61e7e0990be4a34970a314e5905.jpg";
  3. Request request = new Request.Builder().url(img_url).build();
  4. OkHttpClient client = new OkHttpClient();
  5. client.newCall(request).enqueue(new Callback() {
  6. @Override
  7. public void onFailure(Call call, IOException e) {
  8. e.printStackTrace();
  9. }
  10. @Override
  11. public void onResponse(Call call, Response response) throws IOException {
  12. try (InputStream input = response.body().byteStream()) {
  13. File image = new File("src/main/resources/img.jpg");
  14. Files.copy(input, image.toPath(), StandardCopyOption.REPLACE_EXISTING);
  15. }
  16. }
  17. });
  18. }

上传文件

和下载文件相对应的就是上传文件。在资源文件夹src/main/resources中新建一个文本文件(因为上传图片什么的太大了),取名hello.txt,内容随便写点什么。然后用下面的代码就可以上传文件了。需要特别提一点,我这个例子是将文件作为表单内容以表单形式提交的。网上很多例子是直接将文件内容作为数据提交的,这两种方法直接有一些差别,一会儿会提到。

  1. static void uploadFile() throws IOException {
  2. String url = "http://httpbin.org/post";
  3. File file = new File("src/main/resources/hello.txt");
  4. OkHttpClient client = new OkHttpClient();
  5. RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), file);
  6. MultipartBody multipartBody = new MultipartBody.Builder()
  7. .setType(MultipartBody.FORM)
  8. .addFormDataPart("file", file.getName(), requestBody)
  9. .build();
  10. Request request = new Request.Builder()
  11. .url(url)
  12. .post(multipartBody)
  13. .build();
  14. client.newCall(request).enqueue(new Callback() {
  15. @Override
  16. public void onFailure(Call call, IOException e) {
  17. e.printStackTrace();
  18. }
  19. @Override
  20. public void onResponse(Call call, Response response) throws IOException {
  21. String body = response.body().string();
  22. System.out.println(body);
  23. }
  24. });
  25. }

上面的代码执行结果如下。可以看到,文件内容处于files部分,这是用表单形式提交文件的标志。

  1. -------上传文件--------
  2. {
  3. "args": {},
  4. "data": "",
  5. "files": {
  6. "file": "hello world."
  7. },
  8. "form": {},
  9. "headers": {
  10. "Accept-Encoding": "gzip",
  11. "Connection": "close",
  12. "Content-Length": "211",
  13. "Content-Type": "multipart/form-data; boundary=92eedd36-cbcc-487b-8b62-c8161356fb2e",
  14. "Host": "httpbin.org",
  15. "User-Agent": "okhttp/3.10.0"
  16. },
  17. "json": null,
  18. "origin": "110.18.236.170",
  19. "url": "http://httpbin.org/post"
  20. }

前面提到的另外一种将文件内容作为数据提交的代码形式如下,这种形式没有使用MultipartBody。

  1. RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), file);
  2. Request request = new Request.Builder()
  3. .url(url)
  4. .post(requestBody)
  5. .build();

代码运行结果如下,可以看到文件内容跑到了data部分,files部分什么都没有。

  1. -------上传文件--------
  2. {
  3. "args": {},
  4. "data": "hello world.",
  5. "files": {},
  6. "form": {},
  7. "headers": {
  8. "Accept-Encoding": "gzip",
  9. "Connection": "close",
  10. "Content-Length": "12",
  11. "Content-Type": "text/plain",
  12. "Host": "httpbin.org",
  13. "User-Agent": "okhttp/3.10.0"
  14. },
  15. "json": null,
  16. "origin": "110.18.236.170",
  17. "url": "http://httpbin.org/post"
  18. }

最后再提一点,上传文件无外乎就是这两种形式,没有其他的办法了。当然如果你硬要将某些API组合起来的话也可以运行,但是运行结果基本上就是这两种之一。我一开始就是用错了一个方法,导致一直是第二种结果,最后才发现我代码写错了,修改之后变成了第一种表单形式的上传。

以上就是OkHttp的一些简单用法,希望对大家有所帮助。OkHttp库的缺点就是没有官方文档,大概作者觉得这个库使用起来很简单,干脆就不写文档了。不过虽然没有文档,但是官方上给出了大量例子,这些例子都很简单,大家应该看一眼就能明白。我的代码在Github上,有兴趣的同学可以看看。

发表评论

表情:
评论列表 (有 0 条评论,245人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Boost简介

    [Boost库][Boost]由C++标准委员会库工作组成员发起,其中有些内容有望成为下一代C++标准库内容。在C++社区中影响甚大,是不折不扣的“准”标准库。 字符串和文

    相关 Aspose.CAD简介

    [Aspose.CAD][]是用于.Net和Java平台的独立软件库,可读取CAD文件(例如DWG,DXF,DNG,IFC,STL文件)并将其内容导出为PDF文件和光栅图像。

    相关 OkHttp简介

    一直以来,Java并没有什么比较好用的HTTP库,JDK自带的HTTP类又非常旧,难以使用。今天我发现了一个使用比较广泛的[OkHttp][]库,它在安卓和Java领域都有使用