参考链接:
square: http://square.github.io/okhttp/
github: https://github.com/square/okhttp
Okhttp是square推出的一个支持Http1.1和Http2.0的客户端。打开上面的链接,就可以看到square官方的简短介绍,以及示例代码。okhttp支持同步和异步请求。HttpURLConnection和Httpclient本身是没有对异步的支持的,需要的话可以自己封装。Android之前推出的Volley是对httpclient和httpurlconnection的封装。(根据不同的版本选择使用HttpClient还是 HttpURLConnection).
个人认为,OkHttp3最大的好处就是接口使用方便,官方文档里也这么说了:
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支持 Android 2.3及以上,以及java1.7及以上。
下面把官方的使用例子贴出来.例子中使用的是同步方法,异步方法调用equeue把call扔进队列,然后设置callback即可,与其他异步机制使用大同小异。
GET:
package okhttp3.guide;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetExample {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
POST:
package okhttp3.guide;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PostExample {
public static final MediaType JSON = MediaType.get("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();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
String bowlingJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1367702411696,"
+ "'dateStarted':1367702378785,"
+ "'players':["
+ "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
+ "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
+ "]}";
}
public static void main(String[] args) throws IOException {
PostExample example = new PostExample();
String json = example.bowlingJson("Jesse", "Jake");
String response = example.post("http://www.roundsapp.com/post", json);
System.out.println(response);
}
}