OkHttp3使用
1、OkHttp的github地址:github地址
2、导入项目中
3、写请求 get使用
String url = "http://192.168.0.102:8080/ssDemo/user/test";
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder() .url(url) .build();
Call call = okHttpClient.newCall(request);
// Response response = call.execute();
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("返回数据"+e);
Log.e("getRequest", "getRequest: 错误");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("返回数据"+response.body().string());
Log.e("getRequest", "getRequest: 返回数据");
}
});
4、post请求
String url = "http://192.168.0.102:8080/ssDemo/user/findUserById";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("id","1")
.build();
Request request = new Request.Builder() .url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("返回数据"+e);
Log.e("getRequest", "getRequest: 错误");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("返回数据"+response.body().string());
Log.e("getRequest", "getRequest: 返回数据");
}
});