官方文档:https://github.com/square/okhttp/wiki/Recipes
https://github.com/square/okhttp
以下只考虑小数据量请求,比如请求rest json API
相关注意点
1. okhttp3比较多的地方使用了builder模式,OkHttpClient、Request、FormBody等都可以通过<Class>.Builder()获取相应的Builder,进而进行相关的配置。
2. ResponseBody用完了要及时关闭
Each response body is backed by a limited resource like a socket (live network responses) or an open file (for cached responses). Failing to close the response body will leak these resources and may ultimately cause the application to slow down or crash. Close the response body by calling either close()
, byteStream().close()
, or reader().close()
. The bytes()
and string()
methods both close the response body automatically.
相关请求代码
首先创建一个自定义的Response(这个个人喜好)
public static class Response { public Integer code; public String content; }
Get请求
/** * http get 请求 * @param url 请求uri * @return Response请求结果实例,通过response.code==200判断是否有效 */ public static Response httpGet(String url) { Response response = new Response(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); proceedRequest(client, request, response); return response; }
此处的通用处理请求函数
private static void proceedRequest(OkHttpClient client, Request request, Response response) { try { okhttp3.Response temp = client.newCall(request).execute(); response.code = temp.code(); ResponseBody body = temp.body(); if (temp.isSuccessful()) { //call string auto close body response.content = body.string(); } else { response.content = "网络请求失败"; temp.body().close(); } } catch (IOException e) { e.printStackTrace(); Log.w(TAG, e.getMessage() == null ? " " : e.getMessage()); response.code = -1; response.content = e.getMessage(); } }
Post Json字符串请求
/** * http post 请求 * @param url 请求url * @param jsonStr post参数 * @return Response请求结果实例,通过response.code==200判断 */ public static Response httpPost(String url, String jsonStr) { Response response = new Response(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, jsonStr); Request request = new Request.Builder() .url(url) .post(body) .build(); proceedRequest(client, request, response); return response; }
Post Form请求
/** * http post 请求 * @param url 请求url * @param para post参数,表单键值对 * @return HttpResponse请求结果实例 */ public static Response httpPostForm(String url, Map<String, String> para) { if (para == null || para.size() == 0) return null; Response response = new Response(); OkHttpClient client = new OkHttpClient(); FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, String> entry : para.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } RequestBody formBody = builder.build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); proceedRequest(client, request, response); return response; }
Put Json字符串请求
和post非常类似
/** * http put 请求 * @param url 请求url * @param jsonStr post参数 * @return Response请求结果实例,通过response.code==200判断 */ public static Response httpPut(String url, String jsonStr) { Response response = new Response(); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, jsonStr); Request request = new Request.Builder() .url(url) .put(body) .build(); proceedRequest(client, request, response); return response; }
如果Request中需要携带自定义的header信息
Request request = new Request.Builder() .url(getPayPalAccessTokenUrl()) .header("Accept", "application/json") .header("Content-Type", "application/x-www-form-urlencoded") .header("Authorization", "some secret token") .post(body) .build();
如果需要添加自定义的SSL规则
1) 自定义SSL类,比如强制使用TLSv1.2协议
/** * XZTLSSocketFactory.java * * Created by xuanzhui on 2016/3/18. * Copyright (c) 2016 xuanzhui. All rights reserved. */ package cn.beecloud; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class XZTLSSocketFactory extends SSLSocketFactory { private SSLSocketFactory delegate; public XZTLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { SSLContext context = SSLContext.getInstance("TLSv1.2"); context.init(null, null, null); delegate = context.getSocketFactory(); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose)); } @Override public Socket createSocket(String host, int port) throws IOException { return enableTLSOnSocket(delegate.createSocket(host, port)); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return enableTLSOnSocket(delegate.createSocket(host, port)); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); } private Socket enableTLSOnSocket(Socket socket) { if(socket != null && (socket instanceof SSLSocket)) { ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.2"}); } return socket; } }
2) 设置OkHttpClient
OkHttpClient client = new OkHttpClient.Builder() //定义连接超时 .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS) //自定义SSL协议 .sslSocketFactory(new XZTLSSocketFactory()).build();
Client socket:
Protocol | Supported (API Levels) | Enabled by default (API Levels) |
SSLv3 | 1+ | 1+ |
TLSv1 | 1+ | 1+ |
TLSv1.1 | 16+ | 20+ |
TLSv1.2 | 16+ | 20+ |
Server socket:
Protocol | Supported (API Levels) | Enabled by default (API Levels) |
SSLv3 | 1+ | 1+ |
TLSv1 | 1+ | 1+ |
TLSv1.1 | 16+ | 16+ |
TLSv1.2 | 16+ | 16+ |
意味着API level 16+ (Android 4.1, Jelly Bean)是支持TLSv1.2的最低版本要求
ref Android 4.1+ enable TLS 1.1 and TLS 1.2
如果遇到错误
java.lang.IllegalStateException: Unable to extract the trust manager on okhttp3.internal.Platform
将成员变量SSLSocketFactory重名为delegate
ref https://github.com/square/okhttp/issues/2323
相关推荐
原文地址:http://blog.csdn.net/donkor_/article/details/53589316。OkHttp3同步/异步Get请求天气预报与Gson处理复杂JSON字符串。内含最新jar包:gson-2.8.0.jar,okhttp-3.5.0.jar,okio-1.11.0.jar
通过一个完整的java示例来演示如何通过okhttp来调用远程的sse流式接口 背景:我们有一个智能AI的聊天界面,需要调用三方厂商的大模型chat接口,返回答案(因为AI去理解并检索你的问题的时候这个是比较耗时的,这个...
基于OkHttp3封装的网络请求库 功能点 支持Http/Https协议/自定义Https证书认证 支持同步/异步请求 支持异步延迟执行 支持Post/Get/Put/Delete请求 支持Cookie持久化,支持Gzip压缩 支持协议头参数Head设置 支持二...
OkHttp发送请求后,可以通过同步或异步地方式获取响应。下面就同步和异步两种方式进行介绍。 1.1、同步方式 发送请求后,就会进入阻塞状态,知道收到响应。下面看一个下载百度首页的例子: OkHttpClient client = ...
OkHttp3Demo博客地址OkHttp3入门介绍OkHttp3入门介绍之Cookie持久化服务端地址简介OkHttp是一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,本文主要介绍OkHttp3的基本使用方法。结合自己的项目经验,主要...
打造终极MVP+Retrofit2+okhttp3+Rxjava2网络请求,开发实用,简约 简书同步地址:https://www.jianshu.com/p/df4eee78085c
它支持同步阻塞请求和异步回调请求。你可以试试OKHTTP而不重写网络代码。okhttp-urlconnection模块实现了都很熟悉的java.net.HttpURLConnection的API,okhttp-apache模块实现了Apache的HttpClient的API。OKHTTP支持...
okHttp的get同步异步请求,post上传键值对、JSON、文件
封装的get同步请求,get异步请求,post异步提单,从url下载文件。
OkHttp3入门准备工作添加依赖设置网络权限创建简单创建四步走异步请求同步请求中止请求具体介绍GET请求POST请求下载(保存到本地)简单的下载请求(示例)准备工作显示下载进度上传文件上传文件上传(简单示例)涉及...
基于OkHttp链式调用的网络请求库,支持同步的GET 、POST;异步的GET、POST;
聚合数据 OKHttp3.0封装 。满足一般开发, get同步请求 ,get异步请求, post表单提交。 文件远程下载 。不错的联系代码
OkHttp 作为一个简洁高效的 HTTP ...本文对 OkHttp 进行了详细的介绍,包括同步和异步调用、HTTP GET 和 POST 请求处理、用户认证、响应缓存和拦截器等。对于新开发的 Java 应用,推荐使用 OkHttp 作为 HTTP 客户端。
简单注释,通俗易懂,实现okhttp基本功能:1、Get请求(同步和异步); 2、POST请求表单(key-value); 3、POST请求提交(JSON/String等); 4、文件下载; 5、文件上传; 6、图片缓存加载
封装OkHttp3 支持多线程异步请求 支持Http / Https协议 支持同步/异步请求 支持初步逐步执行 支持Cookie持久化 支持JSON,表单提交 支持文件和图片上传/批量上传,支持同步/逐步上传,支持进度提示 支持文件流上传 ...
基于OkHttp3封装的网络请求库 功能点 支持Http/Https协议/自定义Https证书认证 支持同步/异步请求 支持异步延迟执行 支持Post/Get/Put/Delete请求 支持Cookie持久化,支持Gzip压缩 支持协议头参数Head设置 支持二...
OkHttp 除了支持常用的同步 HTTP 请求之外,还支持异步 HTTP 请求调用。在使用同步调用时,当前线程会被阻塞,直到 HTTP 请求完成。当同时发出多个 HTTP 请求时,同步调用的性能会比较差。这个时候通过异步调用可以...
当此 Url 地址存在下载或者上传的动作时,框架会主动调用所有使用此 Url 地址注册过的监听器,达到多个模块的同步更新.框架的构思和实现可以看这篇文章Feature使用简单,只需一行代码即可实现进度监听.多平台支持,...
本篇文章主要介绍了android中实现OkHttp下载文件并带进度条,OkHttp是比较火的网络框架,它支持同步与异步请求,支持缓存,可以拦截,更方便下载大文件与上传文件的操作,有兴趣的可以了解一下