第三方开源库:OkHttp

参考:
Android OkHttp完全解析 是时候来了解OkHttp了
okhttp3的使用

简介

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

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

使用封装

这样我们只需要调用一行代码就可以实现请求数据,提高了代码的简洁性。

UserRequest.getInstance().AsyncPost("cui", "123456");

重写这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成功后发送的结果
}

怎么设置网络请求的缓存?

一网打尽OkHttp中的缓存问题

OkHttpClient client = new OkHttpClient.Builder()  
       .connectTimeout(5, TimeUnit.SECONDS)  
       .cache(new Cache(new File(this.getExternalCacheDir(), "okhttpcache"), 10 * 1024 * 1024))  
       .build();

如果设置具体存活时间,必须适应CacheCtrol

源码

OkHttpDemo02

网络请求框架(一):android-async-http
网络请求框架(二):xUtils
网络请求框架(三):Volley

Volley的使用(一):get+post
Volley的使用(二):加载网络图片
Volley的使用(三):Volley与Activity的联动 + Volley的二次封装

网络请求框架(四):OkHttp

网络请求框架(五):Retrofit

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值