美文网首页
OkHttp3(二)--实例使用

OkHttp3(二)--实例使用

作者: azu_test | 来源:发表于2019-01-24 11:07 被阅读0次

使用前的准备

    public static final String BAI_DU = "https://www.baidu.com";
    public static final String TAO_BAO = "http://api.k780.com:88/?app=phone.get&phone=13800138000&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
    public static final String TAO_BAO_HTTP = "http://api.k780.com:88";
    public static final String UPLOAD_FILE_HTTP = "https://api.github.com/markdown/raw";
    public static final String IMAGE_URL_1 = "https://ss.csdn.net/p?https://mmbiz.qpic.cn/mmbiz_jpg/trm5VMeFp9mJejJH2asZZT0ML63erOW3QAMSkjEMsLwByykbJwsHj7QmPbQDDUU43BJpHTXxyiaY24LXlA6zKDQ/640?wx_fmt=jpeg";
    public static final String IMAGE_URL_2 = "http://imgup01.myra2.com/2017-04/13/11/1492055267740_0.jpg";

依赖OkHttp3框架

dependencies {
    /** 添加网络数据为Gson的数据*/
    implementation "com.google.code.gson:gson:2.8.0"
    /** 添加网络框架OkHttp3*/
    implementation 'com.squareup.okhttp3:okhttp:3.12.1'
    /** 添加网络框架OkHttp3 的依赖io组件*/
    implementation 'com.squareup.okio:okio:1.7.0'
}

实例化OkHttpClient

    private void initData() {
        File sdCache = mContext.getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder().
                connectTimeout(15,TimeUnit.SECONDS).
                writeTimeout(20,TimeUnit.SECONDS).
                readTimeout(20,TimeUnit.SECONDS).
                cache(new Cache(sdCache.getAbsoluteFile(),cacheSize));
        mOkHttpClient = okHttpClientBuilder.build();
    }

1. 异步Get请求

    public static void getRequest(OkHttpClient okHttpClient, String url,final TextView textView){
        Request.Builder requestBuilder = new Request.Builder().
                url(url).
                method("GET",null);
        Request request = requestBuilder.build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new CallbackToMainThread(new CallbackToMainThread.Callback<String>() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response){
                textView.setText(response);
            }

            @Override
            public String getTClassName() {
                return String.class.getName();
            }
        }));
    }

1.上面是简单的使用Get的异步请求,如果想用同步请求的话可以调用Call.execute()方法。
2.正常情况下结果回调是在子线程内的,这里为什么能在回调内更新UI是因为做了一个简单的封装让回调回到UI线程内执行。
3.具体的CallbackToMainThread类会在后面做具体的分析。

2. 异步Post请求

    public static void postRequest(OkHttpClient okHttpClient, String url,final TextView textView){
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("app","phone.get").
                add("phone","13800138000").
                add("appkey","10003").
                add("sign","b59bc3ef6191eb9f747dd4e83c99f2a4").
                add("format","json");
        RequestBody requestBody = formBodyBuilder.build();

        Request request = new Request.Builder().
                url(url).
                post(requestBody).
                build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new CallbackToMainThread(new CallbackToMainThread.Callback<String>() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response){
                JsonModel jsonModel = new Gson().fromJson(response,JsonModel.class);
                String result = "success:"+jsonModel.success+"\n"+"status:"+jsonModel.result.status+"\n"+
                        "phone:"+jsonModel.result.phone+"\n"+"area:"+jsonModel.result.area+"\n"+
                        "postNum:"+jsonModel.result.postNum+"\n"+"att:"+jsonModel.result.att+"\n"+
                        "type:"+jsonModel.result.type+"\n"+"par:"+jsonModel.result.par+"\n"+
                        "prefix:"+jsonModel.result.prefix+"\n"+"operators:"+jsonModel.result.operators+"\n"+
                        "styleSimCall:"+jsonModel.result.styleSimCall+"\n"+"styleCityName:"+jsonModel.result.styleCityName;

                textView.setText(result);
            }

            @Override
            public String getTClassName() {
                return String.class.getName();
            }
        }));
    }

1.通过RequestBody传递请求参数。
2.通过FormBody.Builder来封装并生成RequestBody。
3.通过Gson解析Json数据

3. 异步上传文件

    public static void postFileRequest(OkHttpClient okHttpClient, String url,final TextView textView){
        MediaType mediaType = MediaType.parse("text/x-markdown;  charset=utf-8");
        String filePath = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        }else {
            return;
        }
        File file = new File(filePath,"wuyazhou.txt");
        Request request = new Request.Builder().
                url(url).
                post(RequestBody.create(mediaType,file)).
                build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new CallbackToMainThread(new CallbackToMainThread.Callback<String>() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogShowUtil.addLog("OkHttp",e.getMessage());
                textView.setText("error");
            }

            @Override
            public void onResponse(Call call, String response) throws IOException {
                textView.setText(response);
            }

            @Override
            public String getTClassName() {
                return String.class.getName();
            }
        }));
    }

1.异步上传文件本质是Post请求。
2.通过RequestBody.create(mediaType,file)方法生成要上传的RequestBody。
3.MediaType决定上传文件的类型。

4. 异步下载文件

    public static void getImageRequest(OkHttpClient okHttpClient, String url, final ImageView imageView){
        Request request = new Request.Builder().url(url).method("GET",null).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new CallbackToMainThread(new CallbackToMainThread.Callback<Bitmap>() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogShowUtil.addLog("OkHttp",e.getMessage());
            }

            @Override
            public void onResponse(Call call, Bitmap response) throws IOException {
                imageView.setImageBitmap(response);
            }

            @Override
            public String getTClassName() {
                return Bitmap.class.getName();
            }
        }));
    }

1.异步下载文件本质是Get请求。
2.此处我们做了简单的封装,将返回数据转化成了Bitmap。

5. 异步上传Multipart文件

    public static void postMultipartRequest(OkHttpClient okHttpClient, String url, final TextView textView){
        MediaType mediaType = MediaType.parse("text/x-markdown;  charset=utf-8");
        String filePath = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        }else {
            return;
        }
        File file = new File(filePath,"wuyazhou.txt");

        RequestBody requestBody = new MultipartBody.Builder().
                setType(MultipartBody.FORM).
                addFormDataPart("title","wuyazhou").
                addFormDataPart("txt","wuyazhou.txt",RequestBody.create(mediaType,file)).
                build();
        Request request = new Request.Builder().url(url).post(requestBody).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new CallbackToMainThread(new CallbackToMainThread.Callback<String>() {
            @Override
            public void onFailure(Call call, IOException e) {
                textView.setText("只是一个示例,不会成功的");
            }

            @Override
            public void onResponse(Call call, String response) throws IOException {
                textView.setText(response);
            }

            @Override
            public String getTClassName() {
                return String.class.getName();
            }
        }));
    }

1.通过MultipartBody.Builder来封装要上传的文件和请求参数。
2.MultipartBody.Builder().build()生成要上传的RequestBody。

6. CallbackToMainThread单独开篇介绍,地址如下:
https://www.jianshu.com/p/df0ff5ab5f25

相关文章

网友评论

      本文标题:OkHttp3(二)--实例使用

      本文链接:https://www.haomeiwen.com/subject/ltryjqtx.html