OkHttp

OkHttp3的使用

导入开源库

1
compile 'com.squareup.okhttp3:okhttp:3.6.0'

简单的使用

GET方式

1
2
3
4
5
6
7
8
9
10
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方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
}