okhttp 的使用
①在OK HTTP 的GitHub上下载 jar 包 或者添加 grad'le依赖 OK HTTP 的地址 : https://github.com/square/okhttp
②导入jar包不想导入jar包 添加依赖见下图 。
② 添加依赖 ↓。
③导入jar包 或 添加gradle依赖后,重新编译项目。
上代码:
//1.使用okHttp进行网络请求
OkHttpClient okHttpClient = new OkHttpClient();
//2.创建Request对象-建造者模式
final Request request = new Request.Builder().url(Constant.ADS_URL).build();
//3.调用new Call方法
Call call = okHttpClient.newCall(request);
//同步请求调用execute 异步调用enqueue方法
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//请求成功-response
if (!response.isSuccessful()){
Log.e(getClass().getSimpleName(),"isSuccessful"+"响应未成功");
return;
}
ResponseBody body = response.body();
String string = body.string();
Log.e(getClass().getSimpleName(),"isSuccessful"+string);
}
Created by Leon in shanghai. Copyright © Leon. All rights reserved. 标签:call,jar,Call,使用,okhttp,new,response From: https://www.cnblogs.com/sexintercourse/p/17020528.html