OkHttp在api 4.4之后替换了HttpClient网络交互,4.4之后看到的就是OkHttp,相信大家使用过api 4.4以后的都知道了吧。
1)OkHttp的Get调用方法
//初始化,或得一个OkHttp对象
OkHttpClient client = new OkHttpClient();
//声明一个Request对象,传入一个request对象返回一个Response对象
public 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();
}
}
2)OkHttp的Post调用方法
//声明一个JSON的头文件
public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
//初始化OkHttp对象
OkHttpClient client = new OkHttpClient();
public 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();
}
}
// 构造一个json串,作为调用时传入的参数
public 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}"
+ "]}";
}