1. Using OkHttp forefficient network access(使用okhttp高效的网络通信)
1.1. What is OkHTTP?(什么是okhttp)
OkHTTP (http://square.github.io/okhttp/)is an Open Source project designed to be an efficient HTTP client. It supportsthe SPDY protocol. SPDY is the basis for HTTP 2.0 and allows multiple HTTPrequests to be multiplexed over one socket connection.
OkHttp(http://square.github.io/okhttp/)是开源的高效的http客户端。它支持SPDY协议,SPDY是Http2.0的基础,同时允许多类型的Http请求,可以混合多条socket连接。
If you are using Maven or Gradle as build system you can simply add adependency to group ID com.squareup.okhttp, artifactId, okhttp and the version 2.1.0 (current as of this writing).
如果你是正在使用Maven或者Grandle作为你的系统编译工具,你可以简单的添加依赖集成ID com.squareup.okhttp,okhttp的版本
compile'com.squareup.okhttp:okhttp:2.5.0'
As of Android 5.0 OkHttp is part of the Android platform and is used for all HTTP calls. Android 5.0开始支持所有的okhttp所有的http调用 |
1.2. Creating request objects for makenetwork calls
创建一个对象做网络调用
To use OkHttp you need to create a Request object.
使用okhttp先要创建一个Request 对象。
//avoid creating several instances, should be singleon
OkHttpClient client =new OkHttpClient();
Request request =new Request.Builder()
.url("http://www.vogella.com/index.html")
.build();
You can also add parameters
你也可以添加一些请求参数。
HttpUrl.Builder urlBuilder =HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v","1.0");
urlBuilder.addQueryParameter("user","vogella");
String url =urlBuilder.build().toString();
Request request =new Request.Builder()
.url(url)
.build();
You can also add authentication headers
你也可以添加验证的请求头。
Request request =new Request.Builder()
.header("Authorization","your token")
.url("https://api.github.com/users/vogella")
.build();
1.3. Sending and receiving network calls
发送和接受网络调用
To make a synchronous network call, use the Client to create a Call object anduse the execute method.
实现同步的网络请求,使用Client 创建一个Client 对象,然后调用execute 方法。
Response response =client.newCall(request).execute();
To make asynchronous calls, also create a Call object but use the enqueue method.
实现异步请求,同样需要创建Call 对象,当时使用enqueue 方法。
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Callcall, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Callcall, final Response response)throws IOException {
if(!response.isSuccessful()) {
thrownew IOException("Unexpected code " + response);
}else{
// dosomething wih the result
}
}
Note: If you are using Android and want to update the UI, you need to use Content.runOnUiThread(new Runnable) to sync with the UI thread.
提示:如果你是正在使用Android同时向更新UI,你需要调用 Content.runOnUiThread(newRunnable)去同步UI线程。