博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
第三方开源库:OkHttp
阅读量:4132 次
发布时间:2019-05-25

本文共 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传递值

效果图

这里写图片描述

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();

详细步骤

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();

get异步请求

主要步骤:

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);            }        });    }});

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();

详细步骤:

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();

异步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 创建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();                }            }        });    }});

封装: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;    }}

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; }}

RequestTag

public enum  RequestTag {    GET1,    GET2,    POST1,    POST2,}

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); }}

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);    }}

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); } } /** * 处理网络失败/错误请求 *

直接判断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

你可能感兴趣的文章
码农:组长随便改我代码并且改的也不好,更关键以后还得我维护!
查看>>
没写过js与c#,微软竟能录用我去做这个?当时面试考察的是算法!
查看>>
码农一个月连续出4次技术事故!是个人能力问题还是系统太破?
查看>>
实习生:上次code review得罪了老员工,这次我一句话都不说了!
查看>>
码农吐糟:1年没请过假,1月份想请几天年假回家还被拒了,心酸!
查看>>
码农:2个月跑了4座城市,投了几百封简历还没结果,钱都花完了!
查看>>
码农:休了个年假回来,发现自己的代码被重构了!是你会咋想?
查看>>
码农:一个java开发从来没用过apache或者guava库,这正常么?
查看>>
码农:实现95%以上DBA工作自动化,无人化值守,却革了自己的命!
查看>>
同样的逻辑,两种不同的代码写法,为啥大部分码农喜欢第一种?
查看>>
为什么多数程序员对黑色的界面情有独钟?网友调侃:黑科技般的黑
查看>>
码农吐糟facebook:本来一周4天班,现在却“压榨”到一周上5天!
查看>>
码农在上海4年来深圳后吐糟当地,网友:出国了?还指点江山呢!
查看>>
知乎产品:团建到一半,我司程序员回手掏出电脑改bug!真牛!
查看>>
java码农发帖求挑战技术!网友:给你半小时写个简单虚拟机!
查看>>
985硕士:非科班自学编程感觉还不如培训班出来的,硕士白读了?
查看>>
用mac做开发真的比用windows好么?
查看>>
作为码农,你感觉什么时间写代码思路最清晰?
查看>>
码农:发现了一个好的方案,但改动太大,怕改不好被打脸!咋办?
查看>>
网友诉苦:app体验差就算了!咨询客服被骂“滚”!这么霸气?
查看>>