OkHttp3.0
加入依赖
一:get请求
无非就是3步走
1.创建客户端
2.创建请求
3.发送请求,处理响应
同步Get请求
//创建客户端
OkHttpClient client = new OkHttpClient();
//创建get请求
Request request = new Request.Builder()
.get()
.url("http:www.123.com")
.build();
try {
//客户端发送请求,得到响应
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
return;
}
String result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
异步Get请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//响应成功
String result = response.body().string();
//解析json
}
});
OkHttpClient client = new OkHttpClient();
//创建一个请求体
FormBody body = new FormBody.Builder()
.add("key1","value1")
.add("key2","value2")
.build();
Request request = new Request.Builder()
.url("")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//还可以进行流的对接,读写
String data = response.body().string();
InputStream in = response.body().byteStream();
...
}
});