浅析 - okHttp3使用总结

目录

okHttp

尊重每个人的付出,转载请点这里: http://blog.csdn.net/hanj456/article/details/52424733

注意事项:

  • okHttp3和之前的版本上相比较有些小改动,例如:
    FormEncodingBuilder 被替换成 FormBody ,MultipartBuilder 被替换成 RequestBody;
    okhttp使用MultipartBuilder,FormEncodingBuilder构建post消息体,最终构建出来的都是RequestBody,而okhttp3增加了RequestBody的子类,构造器放到了RequestBody的子类中,MultipartBody.Builder既可以添加表单数据,也可以添加文件等二进制数据

解析类型

MediaType.parse("image/png");  //图片类型
MediaType.parse("audio/mp3");  //音频类型
MediaType.parse("video/mp4");  //视频类型
MediaType.parse("text/x-markdown; charset=utf-8"); //markdown文本类型
MediaType.parse("application/json; charset=utf-8"); //Json数据类型

get请求登录

/**
 * get请求登录
 *
 * @param view
 */
public void getLogin(View view) {
    new Thread() {
        @Override
        public void run() {
            super.run();
            OkHttpClient client = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url("http://10.0.2.2:8080/0903/LoginServlet?name=jack&pwd=123")
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i(TAG, "onResponse: "+response.body().string());
                }
            });
        }
    }.start();
}

get请求获取图片


    /**
     * get请求获取图片
     *
     * @param view
     */
    public void getImage(View view) {

        new Thread() {
            @Override
            public void run() {
                super.run();
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://10.0.2.2:8080/0903/tang3.jpg")
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()){
                            //get the stream
                            InputStream is = response.body().byteStream();
                            //change the stream to bimap
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            //new a file to save bitmap
                            File file = new File("/sdcard/tang3.jpg");
                            file.createNewFile();
                            FileOutputStream fos = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
                            fos.close();
                        }
                    }
                });

            }
        }.start();
    }

get请求获取文件

/**
     * get请求获取文件
     *
     * @param view
     */
    public void getFile(View view) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/0903/okhttp-3.4.1.jar")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    InputStream is = response.body().byteStream();
                    File file = new File("/sdcard/test.jar");
                    FileOutputStream fos = new FileOutputStream(file);
                    int len=0;
                    byte[] bytes = new byte[1024];
                    while ((len=is.read(bytes))!=-1){
                        fos.write(bytes,0,len);
                    }
                    is.close();
                    fos.close();
                }

            }
        });
    }

post请求登录

/**
     * post请求登录
     * @param view
     */
    public void postLogin(View view) {

        new Thread() {
            @Override
            public void run() {
                super.run();
                OkHttpClient client = new OkHttpClient();

                RequestBody formbody = new FormBody.Builder()
                        .add("name","jack")
                        .add("pwd","123")
                        .build();
                Request request = new Request.Builder()
                        .url("http://10.0.2.2:8080/0903/LoginServlet")
                        .post(formbody)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()){
                            Log.i(TAG, "result : "+response.body().string());
                        }else {
                            ...
                        }
                    }
                });
            }
        }.start();
    }

post请求上传图片

/**
     * post请求上传图片
     *
     * @param view
     */
    public void postImage(View view) {
        OkHttpClient client = new OkHttpClient();

        RequestBody fileBody = RequestBody
                .create(MediaType.parse("image/png"), new File("/sdcard/qiqiu.jpg"));
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "pic.jpg", fileBody)
                .build();

        Request request = new Request.Builder().url("http://10.0.2.2:8080/0903/UploadServlet")
                .post(body).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                   ...
                }else {
                   ...
                }
            }
        });

    }

post请求上传文件

 /**
     * post请求上传文件
     *
     * @param view
     */
    public void postFile(View view) {

        OkHttpClient client = new OkHttpClient();

        RequestBody fileBody = RequestBody
                .create(MediaType.parse("text/x-markdown; charset=utf-8"), new File("/sdcard/okHttp.md"));
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "ok.md", fileBody)
                .build();
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/0903/UploadServlet")
                .post(body).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    ...
                }else {
                    ...
                }
            }
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值