Okhttp实践

首先在使用之前需要把okhttp加入到项目中,在github上搜索Okhttp即可。下面附上传送门:https://github.com/square/okhttp

compile 'com.squareup.okhttp3:okhttp:3.5.0'
添加在项目的Gradle中,点击同步即可。

1.Git请求:

Okhttp的基本git请求分为四步:

  1. 声明OkhttpClient对象
  2. 构造Request
  3. 把request封装为Call对象
  4. 执行连接
下面就按照这四步执行以下:

    public void doGit() {
        //1.声明OkhttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2.构造Request
        Request.Builder builder = new Request.Builder();
        //指定方式,地址url等等balabala...
        //builder.patch();
        //builder.post();
        //builder.put();
        final Request request = builder.get().url("http://www.imooc.com/").build();
        //3.把Request封装为Call对象
        Call call = okHttpClient.newCall(request);
        //4.执行
        //异步执行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e("onFailure:" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                L.e("Response:");
                String res = response.body().string();
                L.e(res);
            }
        });

        //同步执行
/*        try {
            call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

2.post---传递键值对

基本的post请求包括:

  1. 声明OkhttpClient对象
  2. 构造RequestBody
  3. 构造Request
  4. 把request封装为Call对象
  5. 执行连接
相比较git请求,多了一个构造RequestBody的过程

    public void doPost() {
        //1.声明OkhttpClient对象
        okHttpClient = new OkHttpClient();
        //2.构造RequestBody
        FormBody.Builder formBody = new FormBody.Builder();
        RequestBody requestBody = formBody.add("email", "abc@hotmail.com").add("password", "12345678").build();
        //3.构造Request
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(BASE_URL + "wms/user-authentication/login").post(requestBody).build();
        //4.请求
        executeRequest(request);
    }

post---传递String给服务器:

    //传递键值对给服务器
    private void doPostString() {
        //相比较post,构造RequestBody的方法有变化
        okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;chaset=utf-8"), "{username:xxxx,password:123}");
        //3.构造Request
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(BASE_URL + "wms/user-authentication/login").post(requestBody).build();
        //4.请求
        executeRequest(request);
    }

post---传递File给服务器:

    //传递File给服务器
    private void doPostFile() {
        //1.地址
        File dir = Environment.getExternalStorageDirectory();
        File file = new File(dir, "img2.jpg");
        if (!file.exists()) {
            L.e("Not Found");
            return;
        }

        //在指定MediaType时,如果不清楚MediaType类型,可以去百度minme type,或者定义为application/octet-stream
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //3.构造Request
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(BASE_URL + "wms/user-authentication/login").post(requestBody).build();
        //4.请求
        executeRequest(request);
    }

post---传递文件给服务器

    //传递文件给服务器
    private void doPostUpload() {
        //1.地址
        File dir = Environment.getExternalStorageDirectory();
        File file = new File(dir, "img2.jpg");
        if (!file.exists()) {
            L.e("Not Found");
            return;
        }

        //创建RequestBody
        MultipartBody.Builder multipartBody = new MultipartBody.Builder();
        RequestBody requestBody = multipartBody.setType(MultipartBody.FORM).addFormDataPart("username", "xuange")
                .addFormDataPart("password", "123")
                //第一个参数:表单域的名称
                //第二个参数:文件传输到服务器之后的名字
                //第三个参数:RequestBody
                .addFormDataPart("mPhoto", "img2.jpg", RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();

        //3.构造Request
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(BASE_URL + "wms/user-authentication/login").post(requestBody).build();
        //4.请求
        executeRequest(request);
    }
3.下载文件

    //下载文件
    private void doDownload() {
        Request.Builder builder = new Request.Builder();
        //指定要下载的网址和内容
        Request request = builder.url(BASE_URL + "files/img2.jpg").get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e("onFailure:" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                int len = 0;
                //指定下载的文件到什么地方和新名称
                File file = new File(Environment.getExternalStorageDirectory(), "img_new.jpg");
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[128];

                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                fos.close();
                is.close();
                L.e("DownLoad Success.");
            }
        });
    }
4.加载图片

    //加载图片
    private void doDownloadImg() {
        okHttpClient = new OkHttpClient();
        Request.Builder builder = new Request.Builder();
        //指定要加载图片的网址
        Request request = builder.get()
                .url("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1483953515130&di=16d55ab916df59571fd13dcc45bd8fc3&imgtype=0&src=http%3A%2F%2Fimg.hb.aicdn.com%2Fd2024a8a998c8d3e4ba842e40223c23dfe1026c8bbf3-OudiPA_fw580")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e("onFailure:" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(is);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imgview.setImageBitmap(bitmap);
                    }
                });
                L.e("DownLoad Success.");
            }
        });
    }

上面抽取出来的call:

    private void executeRequest(Request request) {
        Call call = okHttpClient.newCall(request);
        //4.执行
        //异步执行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e("onFailure:" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                L.e("Response:");
                res = response.body().string();
                L.e(res);
                handler.sendEmptyMessage(1);
            }
        });

        //同步执行
/*        try {
            call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值