本文共 15609 字,大约阅读时间需要 52 分钟。
参考:
OkHttp是一种网络请求框架,使用的使用需要在module的
build.gradle
添加2种依赖
okHttp需要添加这2中依赖
compile 'com.squareup.okhttp3:okhttp:3.4.2' compile 'com.squareup.okio:okio:1.11.0'
btn1 + btn2 + btn3 + btn4练习使用OkHttp
btn5 + btn6 + btn7 + btn8对OkHttp进行了封装,并使用了EventBus传递值步骤:
1. 创建OkHttpClient对象 2. 创建Request对象 3. 创建Call对象 4. 把请求加入调度
主要步骤
OkHttpClient http = new OkHttpClient(); Request request = new Request.Builder().get().url(url).build(); Response response = http.newCall(request).execute(); String json = response.body().string();
详细步骤
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();
主要步骤:
OkHttpClient http = new OkHttpClient();Request request = new Request.Builder().get().url(url).build();Call call = http.newCall(request);call.enqueue(new Callback() {...}
详细步骤:
//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); } }); }});
主要步骤:
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();
详细步骤:
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();
主要步骤:
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 创建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(); } } }); }});
event有5个类:
RequestTag:请求tag MainReqeust:封装了OkHttp的回调,BaseEvent + HttpEvent + HttpSuccessEvent + HttpErrorEvent + AppEvent
onResponse(...) onFailure(...)
中用EventBus发送数据 UserRequest:请求网络数据的方法全部在里面,把OkHttp的前3步写在这里面,第4布封装在了MainRequest中 BaseActivity:订阅事件总线,接收EventBus发送(post)的数据
已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; }}
HttpEvent :
public class HttpEvent extends BaseEvent { @NonNull private RequestTag requestTag; public RequestTag getRequestTag() { return requestTag; } public void setRequestTag(@NonNull RequestTag requestTag) { this.requestTag = requestTag; }}
HttpSuccessEvent
public class HttpSuccessEvent extends HttpEvent { private String json; public String getJson() { return json; } public void setJson(String json) { this.json = json; }}
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; }}
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; }}
public enum RequestTag { GET1, GET2, POST1, POST2,}
封装了回调
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); }}
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); }}
订阅事件,其余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); } } /** * 处理网络失败/错误请求 *直接判断HttpEvent的RequestTag即可 * * @param event 错误事件 */ public void httpErrorEvent(HttpErrorEvent event) { } /** * 处理网络成功请求 *
直接判断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(); }}
这样我们只需要调用一行代码就可以实现请求数据,提高了代码的简洁性。
UserRequest.getInstance().AsyncPost("cui", "123456");
重写这3个方法用于处理请求的数据
@Overridepublic 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 }}@Overridepublic 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); }}@Overridepublic void applicationEvent(AppEvent event) { super.applicationEvent(event); // TODO: 接收httpSuccessEvent(...)中JsonParser成功后发送的结果}
OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .cache(new Cache(new File(this.getExternalCacheDir(), "okhttpcache"), 10 * 1024 * 1024)) .build();
如果设置具体存活时间,必须适应CacheCtrol
网络请求框架(二):xUtils 网络请求框架(三):Volley