最近在研究OkHttp。当然是从官网看起,但是官网是英文,那就边看边翻译吧。以下是对OkHttp官网-Recipes的翻译。原文地址:https://square.github.io/okhttp/recipes/
用法
我们已经写了一些方法来演示怎样使用OkHttp来解决一些常见问题。通过阅读它们了解如何在一起使用的。自由复制/粘贴这些列子,这就是它们的作用。
同步GET请求
请求一个文件,打印响应头,并且将响应内容作为String打印出来。
string()
方法在获取相应小的文档内容时候是方便且高效的。但是如果相应内容太大,应该避免使用 string()
方法,因为它会加载所有内容到内存中。在这种情况下,更好的方式是把内容当作Stream来处理。
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
异步GET请求
在工作线程(异步)请求一个文件,并且当响应准备好时候被回调。在响应头准备好时候后被回调。获取响应内容仍然有可能阻塞。OkHttp目前不提供异步api来接收部分响应体。
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
})
}
获取Headers
通常HTTP头就像一个Map<String, String>:每个key对应一个可能是空的值。但是有的头允许有多个值,比如 Guava’s Multimap。比如,HTTP响应提供多个Vary 头是合法的也是常见的。OkHttp的API试图让这种情况都变得舒适。
添加Hearders时,使用 header(name, value)
来设置name和value。如果设置的value已存在,就替换以前的值。使用addHeader(name, value)
来添加一个header而不删除已经存在的头。
获取header时,使用header(name)
得到一个最新的value。通常也是唯一的值!如果没有值,header(name)
将返回null。获取一个header的列表使用headers(name)
。
访问所有的headers,使用Headers
类根据索引来访问。
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("https://api.github.com/repos/square/okhttp/issues")
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Accept", "application/json; q=0.5")
.addHeader("Accept", "application/vnd.github.v3+json")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println("Server: ${response.header("Server")}")
println("Date: ${response.header("Date")}")
println("Vary: ${response.headers("Vary")}")
}
}
POST请求String
使用HTTP POST请求发送一个body到服务器。下面的列子发送了一个markdown文档发送到一个把markdown当作HTML来渲染的web服务器。因为整个body会同时加载到内存中,避免使用这个API发送一个大数据(超过1M)。
private val client = OkHttpClient()
fun run() {
val postBody = """
|Releases
|--------
|
| * _1.0_ May 6, 2013
| * _1.1_ June 15, 2013
| * _1.2_ August 11, 2013
|""".trimMargin()
val request = Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN))
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
POST流
这里我们以流的形式发布一个body。 这个请求body的内容是在写入时生成的。 下面的例子直接将流写到Okio缓冲接收器(sink)。 你可能更喜欢使用OutputStream,可以从BufferedSink.outputStream()得到它。
private val client = OkHttpClient()
fun run() {
val requestBody = object : RequestBody() {
override fun contentType() = MEDIA_TYPE_MARKDOWN
override fun writeTo(sink: BufferedSink) {
sink.writeUtf8("Numbers\n")
sink.writeUtf8("-------\n")
for (i in 2..997) {
sink.writeUtf8(String.format(" * $i = ${factor(i)}\n"))
}
}
private fun factor(n: Int): String {
for (i in 2 until n) {
val x = n / i
if (x * i == n) return "${factor(x)} × $i"
}
return n.toString()
}
}
val request = Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
POST一个文件
把文件当作body非常简单。
private val client = OkHttpClient()
fun run() {
val file = File("README.md")
val request = Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(file.asRequestBody(MEDIA_TYPE_MARKDOWN))
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
POST 表单
使用FormBody.Builder
来构建一个类似HTMLform
标签的body。Names和Values会使用兼容HTML表单的URL编码。
private val client = OkHttpClient()
fun run() {
val formBody = FormBody.Builder()
.add("search", "Jurassic Park")
.build()
val request = Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
POST多个请求
MultipartBody.Builder
可以构建复杂的请求体与HTML文件上传表单兼容。 总请求的每个部分本身就是一个请求正文,并且可以定义自己的headers。 如果有,这些headers应该描述它的body,比如它的Content-Disposition
。 如果Content-Length
和Content-Type
头可用,则会自动添加它们。
private val client = OkHttpClient()
fun run() {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
val requestBody = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
File("docs/images/logo-square.png").asRequestBody(MEDIA_TYPE_PNG))
.build()
val request = Request.Builder()
.header("Authorization", "Client-ID $IMGUR_CLIENT_ID")
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
println(response.body!!.string())
}
}
companion object {
/**
* The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running
* these examples, please request your own client ID! https://api.imgur.com/oauth2
*/
private val IMGUR_CLIENT_ID = "9199fdef135c122"
private val MEDIA_TYPE_PNG = "image/png".toMediaType()
}
使用Moshi解析JSON内容
Moshi 是一个方便的API,用于在JSON和Java对象之间进行转换。 下面我们使用它来解码来自GitHub API的JSON内容。
注意ResponseBody.charStream()
使用Content-Type
响应头来选择解码响应内容时使用的字符集。 如果没有指定字符集,默认为UTF-8。
private val client = OkHttpClient()
private val moshi = Moshi.Builder().build()
private val gistJsonAdapter = moshi.adapter(Gist::class.java)
fun run() {
val request = Request.Builder()
.url("https://api.github.com/gists/c2a7c39532239ff261be")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
val gist = gistJsonAdapter.fromJson(response.body!!.source())
for ((key, value) in gist!!.files!!) {
println(key)
println(value.content)
}
}
}
@JsonClass(generateAdapter = true)
data class Gist(var files: Map<String, GistFile>?)
@JsonClass(generateAdapter = true)
data class GistFile(var content: String?)
请求缓存
对于缓存,需要一个可以读写的且是限制大小的缓存目录。这个目录应是私有的,其他不信任的程序不能访问这些内容。
让多个缓存同时访问同一个缓存目录是错误的。 大多数应用程序应该只创建一个OkHttpClient,并配置缓存,在需要地方使用这个实例。 否则,这两个缓存实例将相互践踏,破坏响应缓存,可能使程序崩溃。
缓存配置都使用HTTP头。 你可以添加像Cache-Control: max-stale=3600
这样的请求头,OkHttp的缓存会处理它们。 web服务器用它自己的响应头来配置响应的缓存时间,比如Cache-Control: max-age=9600
。 缓存头可以强制缓存响应、强制网络响应或强制使用有条件的GET验证网络响应。
private val client: OkHttpClient = OkHttpClient.Builder()
.cache(Cache(
directory = cacheDirectory,
maxSize = 10L * 1024L * 1024L // 10 MiB
))
.build()
fun run() {
val request = Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build()
val response1Body = client.newCall(request).execute().use {
if (!it.isSuccessful) throw IOException("Unexpected code $it")
println("Response 1 response: $it")
println("Response 1 cache response: ${it.cacheResponse}")
println("Response 1 network response: ${it.networkResponse}")
return@use it.body!!.string()
}
val response2Body = client.newCall(request).execute().use {
if (!it.isSuccessful) throw IOException("Unexpected code $it")
println("Response 2 response: $it")
println("Response 2 cache response: ${it.cacheResponse}")
println("Response 2 network response: ${it.networkResponse}")
return@use it.body!!.string()
}
println("Response 2 equals Response 1? " + (response1Body == response2Body))
}
如果不想使用缓存,可以使用CacheControl.FORCE_NETWORK
。如果不想使用网络数据,可以使用 CacheControl.FORCE_CACHE
。注意:如果你使用FORCE_CACHE
但是需要请求网络,OkHttp将返回一个504 Unsatisfiable request
响应。
关闭请求
使用Call.cancel()
来立即停止正在进行的请求。如果线程当前正在写入请求或者读取响应,将会收到IOExceptioin
。当不需要请求时,可以使用这个来节约网络资源;比如当用户离开应用时。同步和异步调用都可以取消。
private val executor = Executors.newScheduledThreadPool(1)
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
.build()
val startNanos = System.nanoTime()
val call = client.newCall(request)
// Schedule a job to cancel the call in 1 second.
executor.schedule({
System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f)
call.cancel()
System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f)
}, 1, TimeUnit.SECONDS)
System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f)
try {
call.execute().use { response ->
System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
(System.nanoTime() - startNanos) / 1e9f, response)
}
} catch (e: IOException) {
System.out.printf("%.2f Call failed as expected: %s%n",
(System.nanoTime() - startNanos) / 1e9f, e)
}
}
超时
当无法连接到对方时采用超时失败。网络分区可能是由于客户机连接问题造成的,服务器可用性问题,或者介于两者之间的任何问题。 OkHttp支持连接、写、读和全部请求超时。
private val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.callTimeout(10, TimeUnit.SECONDS)
.build()
fun run() {
val request = Request.Builder()
.url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
.build()
client.newCall(request).execute().use { response ->
println("Response completed: $response")
}
}
其他配置
所有的HTTP客户端的配置都在OkHttpClient
中,包括代理设置,超时和缓存。如果需要改变单个请求的配置,可以使用OkHttpClient.newBuilder()
。这将返回一个Builder,该Builder与原始HttpClient共享相同的连接池(connection pool)、分发器(dispathcher)和配置。 在下面的列子中,我们创建一个500ms超时和一个3000ms超时的请求。
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
.build()
// Copy to customize OkHttp for this request.
val client1 = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build()
try {
client1.newCall(request).execute().use { response ->
println("Response 1 succeeded: $response")
}
} catch (e: IOException) {
println("Response 1 failed: $e")
}
// Copy to customize OkHttp for this request.
val client2 = client.newBuilder()
.readTimeout(3000, TimeUnit.MILLISECONDS)
.build()
try {
client2.newCall(request).execute().use { response ->
println("Response 2 succeeded: $response")
}
} catch (e: IOException) {
println("Response 2 failed: $e")
}
}
身份验证
OkHttp可以自动重试未经验证的请求。当响应是401 Not Authorized
时,将要求Authenticator
提供凭据。下面实现构建一个不包含凭证的请求。 如果没有可用凭据,则返回null以跳过重试。
使用Response.challenges()
可以获得任何身份验证挑战的模式和领域。 在完成Basic
挑战时,使用Credentials.basic(username, password)
编码请求头。
private val client = OkHttpClient.Builder()
.authenticator(object : Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route?, response: Response): Request? {
if (response.request.header("Authorization") != null) {
return null // Give up, we've already attempted to authenticate.
}
println("Authenticating for response: $response")
println("Challenges: ${response.challenges()}")
val credential = Credentials.basic("jesse", "password1")
return response.request.newBuilder()
.header("Authorization", credential)
.build()
}
})
.build()
fun run() {
val request = Request.Builder()
.url("http://publicobject.com/secrets/hellosecret.txt")
.build()
}
为了避免在身份验证不起作用时进行多次重试,可以返回null来放弃。 例如,当已经尝试了这些确切的凭证时,您可能想要跳过重试:
if (credential == response.request.header("Authorization")) {
return null // If we already failed with these credentials, don't retry.
}
当你达到应用程序定义的尝试限制时,你也可以跳过重试:
if (response.responseCount >= 3) {
return null // If we've failed 3 times, give up.
}
上面的代码依赖于这个responseCount
val Response.responseCount: Int
get() = generateSequence(this) { it.priorResponse }.count()