参考资料
[1]. 官方网站,http://square.github.io/okhttp/
[2]. GitHub下载地址,https://github.com/square/okhttp
[3]. 彻底入门OkHttp使用——官方教程解析,
https://m.2cto.com/net/201605/505364.html
[4]. OkHttp3 最有营养的初级教程,
https://www.cnblogs.com/jianyungsun/p/6648390.html
官方的两个例子
直接复制使用
get方法
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetExample {
// 创建客户端
OkHttpClient client = new OkHttpClient();
// 根据url地址运行
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();
// 天气接口 http://www.weather.com.cn/data/sk/101010100.html
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
// 输出请求数据
System.out.println(response);
}
}
post方法
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.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
// 根据json数据创建body
RequestBody body = RequestBody.create(JSON, json);
// 根据body和url地址创建请求
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// 执行请求
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
// 创建一个json数据字符串
String bowlingJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1467702411692,"
+ "'dateStarted':1467702378785,"
+ "'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();
// 返回json字符串
String json = example.bowlingJson("Jesse", "Jake");
// 根据url地址和json请求
String response = example.post("http://www.roundsapp.com/post", json);
// 输出
System.out.println(response);
}
}