关于OkHttp这里附上官方API文档和github地址
compile ‘com.squareup.okhttp3:okhttp:3.8.1’ //目前Android最新版
OkHttp有四大优点:
1 HTTP/2 support allows all requests to the same host to share a socket.
2 Connection pooling reduces request latency (if HTTP/2 isn’t available).
3 Transparent GZIP shrinks download sizes.
4 Response caching avoids the network completely for repeat requests.
Get使用说明:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Post使用说明:
public 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();
}