Overview
HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.
OkHttp is an HTTP client that’s efficient by default:
- HTTP/2 support allows all requests to the same host to share a socket.
- Connection pooling reduces request latency (if HTTP/2 isn’t available).
- Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.
Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.
OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7.
Examples
Get a URL
This program downloads a URL and print its contents as a string. Full source.
1 | OkHttpClient client = new OkHttpClient(); |
Post to a Server
This program posts data to a service. Full source.1
2
3
4
5
6
7
8
9
10
11
12
13
14public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
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();
}
Download
You’ll also need Okio, which OkHttp uses for fast I/O and resizable buffers. Download the latest JAR.
The source code to OkHttp, its samples, and this website is available on GitHub.
Maven
1 | <dependency> |
Gradle
1 | compile 'com.squareup.okhttp3:okhttp:(insert latest version)' |
Contributing
If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.
When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code compiles by running mvn clean verify.
Before your code can be accepted into the project you must also sign the Individual Contributor License Agreement (CLA).
License
1 | Copyright 2016 Square, Inc. |
添加cookie
1 | private static final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>(); |
请求参数
https://github.com/square/okhttp/wiki/Recipes
1 | RequestBody formBody = new FormBody.Builder() |
json转类
1 | Gson gson = new Gson(); |