okhttp的使用详情
程序员文章站
2022-07-13 10:55:00
...
简介
OkHttp是一种网络请求框架,使用的使用需要在module的
build.gradle
添加2种依赖
okHttp需要添加这2中依赖
compile 'com.squareup.okhttp3:okhttp:3.4.2'
compile 'com.squareup.okio:okio:1.11.0'
- 1
- 2
btn1 + btn2 + btn3 + btn4练习使用OkHttp
btn5 + btn6 + btn7 + btn8对OkHttp进行了封装,并使用了EventBus传递值
效果图
OkHttp的使用 :get + post
步骤:
1. 创建OkHttpClient对象
2. 创建Request对象
3. 创建Call对象
4. 把请求加入调度
get请求
get同步请求
主要步骤
OkHttpClient http = new OkHttpClient();
Request request = new Request.Builder().get().url(url).build();
Response response = http.newCall(request).execute();
String json = response.body().string();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
详细步骤
new Thread(new Runnable() {
@Override
public void run() {
//1 创建OkHttpClient对象
OkHttpClient http = new OkHttpClient();
//2 创建请求对象
String url = "http://192.168.1.11:8080/okhttp/json1";
Request request = new Request.Builder().get().url(url).build();
//3 创建回调对象并执行
try {
Response response = http.newCall(request).execute();
final String json = response.body().string();
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(json);
}
});
}
} catch (final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("" + e.getMessage().toString());
}
});
e.printStackTrace();
}
}
}).start();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
get异步请求
主要步骤:
OkHttpClient http = new OkHttpClient();
Request request = new Request.Builder().get().url(url).build();
Call call = http.newCall(request);
call.enqueue(new Callback() {...}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
详细步骤:
//1 创建OkHttpClient对象
OkHttpClient http = new OkHttpClient();
//2 创建Request对象
String url = "http://192.168.1.11:8080/okhttp/json2";
Request request = new Request.Builder().get().url(url).build();
//3 创建回调对象
Call call = http.newCall(request);
//4 执行
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(e.getMessage().toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String json = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(json);
}
});
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
post请求
同步post请求
主要步骤:
OkHttpClient http = new OkHttpClient();
FormBody formBody = new FormBody.Builder().add("name", "cqc").add("age","20").build();
Request request = new Request.Builder().post(formBody).url(url).build();
Call call = http.newCall(request);
Response response = call.execute()
String json = response.body().string();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
详细步骤:
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient http = new OkHttpClient();
FormBody formBody = new FormBody.Builder().add("name", "cqc").add("age", "20").build();
String url = "http://192.168.1.11:8080/okhttp/json3";
Request request = new Request.Builder().post(formBody).url(url).build();
Call call = http.newCall(request);
try {
final Response response = call.execute();
final String json = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (response.isSuccessful()) {
tv.setText(json);
} else {
tv.setText("error");
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
异步post请求
主要步骤:
OkHttpClient http = new OkHttpClient();
FormBody formBody = new FormBody.Builder().add("name", "AndroidCQC").add("age", "20").build();
Request request = new Request.Builder().post(formBody).url(url).build();
Call call = http.newCall(request);
call.enqueue(new Callback() {....}
String json = response.body().string();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
详细步骤:
//1 创建OkHttpClient对象
OkHttpClient http = new OkHttpClient();
//2 创建Request对象
FormBody formBody = new FormBody.Builder().add("name", "AndroidCQC").add("age", "20").build();
String url = "http://192.168.1.11:8080/okhttp/json4";
Request request = new Request.Builder().post(formBody).url(url).build();
//3 创建回调对象
Call call = http.newCall(request);
//4 执行回调
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(e.getMessage().toString());
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String json = response.body().string();
tv.setText(json);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
封装:OkHttp + EventBus
event有5个类:
BaseEvent + HttpEvent + HttpSuccessEvent + HttpErrorEvent + AppEvent
RequestTag:请求tag
MainReqeust:封装了OkHttp的回调,onResponse(...) onFailure(...)
中用EventBus发送数据
UserRequest:请求网络数据的方法全部在里面,把OkHttp的前3步写在这里面,第4布封装在了MainRequest中
BaseActivity:订阅事件总线,接收EventBus发送(post)的数据
event
已BaseEvent + HttpSuccessEvent为例
BaseEvent
public class BaseEvent {
private int id;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
HttpEvent :
public class HttpEvent extends BaseEvent {
@NonNull
private RequestTag requestTag;
public RequestTag getRequestTag() {
return requestTag;
}
public void setRequestTag(@NonNull RequestTag requestTag) {
this.requestTag = requestTag;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
HttpSuccessEvent
public class HttpSuccessEvent extends HttpEvent {
private String json;
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
HttpErrorEvent :
public class HttpErrorEvent extends HttpEvent {
private int errorCode;
private String errorMessage;
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
AppEvent :
public class AppEvent extends BaseEvent {
private Object obj1;
private Object obj2;
private String extraInfo = null;
private String tag;
private int code;
public String getExtraInfo() {
return extraInfo;
}
public void setExtraInfo(String extraInfo) {
this.extraInfo = extraInfo;
}
public Object getObj1() {
return obj1;
}
public void setObj1(Object obj) {
this.obj1 = obj;
}
public Object getObj2() {
return obj2;
}
public void setObj2(Object obj2) {
this.obj2 = obj2;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
RequestTag
public enum RequestTag {
GET1,
GET2,
POST1,
POST2,
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
MainReqeust
封装了回调
public class MainRequest {
private static MainRequest mainRequest;
private MainRequest() {
super();
}
public static MainRequest getInstance() {
if (mainRequest == null) {
mainRequest = new MainRequest();
}
return mainRequest;
}
//异步get
public void makeAsyncGetRequest(Call call, final RequestTag tag) {
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpErrorEvent(e, tag);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpSuccessEvent(response.body().string(), tag);
}
});
}
//同步get
public void makeSyncGetRequest(final Call call, final RequestTag tag) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
if (response.isSuccessful()) {
httpSuccessEvent(response.body().string(), tag);
}
} catch (IOException e) {
e.printStackTrace();
httpErrorEvent(e, tag);
}
}
}).start();
}
//异步post
public void makeSyncPostRequest(Call call, final RequestTag tag) {
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpErrorEvent(e, tag);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpSuccessEvent(response.body().string(), tag);
}
});
}
//同步post
public void makeAsyncPostRequest(final Call call, final RequestTag tag) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
if (response.isSuccessful()) {
httpSuccessEvent(response.body().string(), tag);
}
} catch (IOException e) {
e.printStackTrace();
httpErrorEvent(e, tag);
}
}
}).start();
}
private void httpErrorEvent(IOException e, RequestTag tag) {
Log.d("error", "error=" + e.getMessage().toString());
HttpErrorEvent event = new HttpErrorEvent();
event.setErrorMessage("" + e.getMessage().toString());
event.setRequestTag(tag);
EventBus.getDefault().post(event);
}
private void httpSuccessEvent(String json, RequestTag tag) {
Log.d("response", "response=" + json);
HttpSuccessEvent event = new HttpSuccessEvent();
event.setJson(json);
event.setRequestTag(tag);
EventBus.getDefault().post(event);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
UserRequest
app中所有的请求都放在这个类中,类名比较随意,可以自己修改成AppRequest,比较好理解。
public class UserRequest {
private static UserRequest userRequest;
private OkHttpClient http;
private UserRequest() {
super();
http = new OkHttpClient();
}
public static UserRequest getInstance() {
if (userRequest == null) {
userRequest = new UserRequest();
}
return userRequest;
}
//get请求 不带参数
// 同步get
public void syncGet(String name, String pwd) {
String url = "http://192.168.1.11:8080/okhttp/json1";
RequestTag tag = RequestTag.GET1;
Request request = new Request.Builder().url(url).get().build();
Call call = http.newCall(request);
MainRequest.getInstance().makeSyncGetRequest(call, tag);
}
//异步get
public void AsyncGet(String name, String pwd) {
String url = "http://192.168.1.11:8080/okhttp/json2";
RequestTag tag = RequestTag.GET2;
Request request = new Request.Builder().url(url).get().build();
Call call = http.newCall(request);
MainRequest.getInstance().makeAsyncGetRequest(call, tag);
}
//同步post
public void syncPost(String name, String pwd) {
String url = "http://192.168.1.11:8080/okhttp/json3";
RequestTag tag = RequestTag.POST1;
FormBody formBody = new FormBody.Builder().add("name", name).add("pwd", pwd).build();
Request request = new Request.Builder().post(formBody).url(url).build();
Call call = http.newCall(request);
MainRequest.getInstance().makeSyncPostRequest(call, tag);
}
//异步post
public void AsyncPost(String name, String pwd) {
String url = "http://192.168.1.11:8080/okhttp/json4";
RequestTag tag = RequestTag.POST2;
FormBody formBody = new FormBody.Builder().add("name", name).add("pwd", pwd).build();
Request request = new Request.Builder().url(url).post(formBody).build();
Call call = http.newCall(request);
MainRequest.getInstance().makeAsyncPostRequest(call, tag);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
BaseActiviy
订阅事件,其余activity只需要继承即可
public class BaseActivity extends AppCompatActivity {
private ProgressDialogUtil progressDialogUtil;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
progressDialogUtil = new ProgressDialogUtil(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public final void onEventBack(BaseEvent event) {
if (event instanceof HttpErrorEvent) {
//mark error
httpErrorEvent((HttpErrorEvent) event);
} else if (event instanceof HttpSuccessEvent) {
httpSuccessEvent((HttpSuccessEvent) event);
} else {
applicationEvent((AppEvent) event);
}
}
/**
* 处理网络失败/错误请求
* <p>直接判断HttpEvent的RequestTag即可
*
* @param event 错误事件
*/
public void httpErrorEvent(HttpErrorEvent event) {
}
/**
* 处理网络成功请求
* <p>直接判断HttpEvent的RequestTag即可
*
* @param event 成功事件
*/
public void httpSuccessEvent(HttpSuccessEvent event) {
}
/**
* 处理app内部事件
*
* @param event app内部事件
*/
public void applicationEvent(AppEvent event) {
}
public void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void showProgressDialog() {
progressDialogUtil.showDialog();
}
public void dismissProgressDialog() {
progressDialogUtil.dismissDialog();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
使用封装
这样我们只需要调用一行代码就可以实现请求数据,提高了代码的简洁性。
UserRequest.getInstance().AsyncPost("cui", "123456");
- 1
重写这3个方法用于处理请求的数据
@Override
public void httpSuccessEvent(HttpSuccessEvent event) {
super.httpSuccessEvent(event);
if (event.getRequestTag() == RequestTag.GET1 || event.getRequestTag() == RequestTag.GET2 || event.getRequestTag() == RequestTag.POST1 || event.getRequestTag() == RequestTag.POST2) {
String json = event.getJson();
tv.setText(json);
// TODO: 解析数据可以再写一个类JsonParser,将解析结果用EventBus发送过来,EventBus.getDefault().post(event);其中event是AppEvent
}
}
@Override
public void httpErrorEvent(HttpErrorEvent event) {
super.httpErrorEvent(event);
if (event.getRequestTag() == RequestTag.GET1 || event.getRequestTag() == RequestTag.GET2 || event.getRequestTag() == RequestTag.POST1 || event.getRequestTag() == RequestTag.POST2) {
String json = event.getErrorMessage();
tv.setText(json);
}
}
@Override
public void applicationEvent(AppEvent event) {
super.applicationEvent(event);
// TODO: 接收httpSuccessEvent(...)中JsonParser成功后发送的结果
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
怎么设置网络请求的缓存?
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.cache(new Cache(new File(this.getExternalCacheDir(), "okhttpcache"), 10 * 1024 * 1024))
.build();
- 1
- 2
- 3
- 4