Android okHttp的简单使用

本文主要展示  okHttp 插件的基本用法,

主要包含  

1.get方式请求数据

2.post方式请求数据

3.文件的上传

4.文件的下载

5.加载网络图片


okHttp所需的jar包:

okHttpjar包okio的jar包

布局文件:

布局文件很简单,就五个按钮,一个imageView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.skywalker.okhttptest.MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="123456" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HTTPGet"
        android:id="@+id/httpGet"
        android:layout_below="@+id/text"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HTTPPost"
        android:id="@+id/httpPost"
        android:layout_below="@+id/httpGet"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fileUpload"
        android:id="@+id/fileUpload"
        android:layout_below="@+id/httpPost"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fileDownload"
        android:id="@+id/fileDownload"
        android:layout_below="@+id/fileUpload"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="loadImage"
        android:id="@+id/loadImage"
        android:layout_below="@+id/fileDownload"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ImageView
        android:layout_width="165dp"
        android:layout_height="110dp"
        android:id="@+id/imageView"
        android:layout_below="@+id/loadImage"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


</RelativeLayout>

使用方法:

一、GET方式请求数据

 //1.Get方式请求数据
        httpGet = (Button) findViewById(R.id.httpGet);
        httpGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient mOkHttpClient = new OkHttpClient();
                //创建一个Request
                final Request request = new Request.Builder()
                        .url("http://haiws.com/")
                        .build();
                //new call
                Call call = mOkHttpClient.newCall(request);


                //请求加入调度
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.i("test", "fail");
                    }

                    @Override
                    public void onResponse(final Response response) throws IOException {
                        //希望获得返回的字符串,可以通过response.body().string()获取
                        //如果希望获得返回的二进制字节数组,则调用response.body().bytes()
                        //想拿到返回的inputStream,则调用response.body().byteStream()
                        //onResponse执行的线程并不是UI线程

                        String htmlStr = response.body().string();
                        Log.i("test", htmlStr);

                    }
                });
            }
        });

二、POST方式请求数据

        //2.POST方式请求数据
        findViewById(R.id.httpPost).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient mOkHttpClient = new OkHttpClient();
                FormEncodingBuilder builder = new FormEncodingBuilder();
                //添加参数
                builder.add("username", "czzccz");
                builder.add("password", "123321");

                Request request = new Request.Builder()
                        .url("http://jk.czlaite.com/openapi/register")
                        .post(builder.build())
                        .build();
                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.i("test", "fail");
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        Log.i("test", response.body().string());
                    }
                });
            }
        });

三、上传文件

        //上传文件
        findViewById(R.id.fileUpload).setOnClickListener(new View.OnClickListener() {
            OkHttpClient mOkHttpClient = new OkHttpClient();

            @Override
            public void onClick(View v) {
                //创建一个文件,用于上传到服务器端
                File file = new File(Environment.getExternalStorageDirectory(), "123123.txt");
                if (!file.exists()) {
                    Log.i("test", "NO FILE");
                    try {
                        file.createNewFile();
                        OutputStream ous = new FileOutputStream(file);
                        ous.write("1234567890".getBytes());
                        ous.flush();
                        ous.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                // 上传文件的步骤
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                //区别POST方式请求数据  FormEncodingBuilder
                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addPart(Headers.of(
                                "Content-Disposition",
                                "form-data; name=\"username\""),
                                RequestBody.create(null, "Sky"))
                        .addPart(Headers.of(
                                "Content-Disposition",
                                "form-data; name=\"mFile\";filename=\"123.txt\""), fileBody)
                        .build();

                Request request = new Request.Builder()
                        .url("http://192.168.0.177:8080/uploadTest/simpleFileupload")
                        .post(requestBody)
                        .build();

                Call call = mOkHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.i("test", ",上传失败");
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        Log.i("test", ",上传成功");
                    }
                    //...
                });
            }
        });


四、下载文件

        //下载文件
        findViewById(R.id.fileDownload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient mOkHttpClient = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url("http://img39.51tietu.net/pic/2017-011003/20170110030923zgwnujrdwlu107946.jpg")
                        .build();
                //new call
                Call call = mOkHttpClient.newCall(request);


                //请求加入调度
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.i("test", "fail");
                    }

                    @Override
                    public void onResponse(final Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            Log.i("test", "response is not success");
                            return;
                        }

                        //希望获得返回的字符串,可以通过response.body().string()获取
                        //如果希望获得返回的二进制字节数组,则调用response.body().bytes()
                        //想拿到返回的inputStream,则调用response.body().byteStream()
                        InputStream ins = response.body().byteStream();
                        File file = new File(Environment.getExternalStorageDirectory(), "123.jpg");
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        OutputStream ous = new FileOutputStream(file);
                        byte[] buff = new byte[1024];
                        int len;
                        while ((len = ins.read(buff)) != -1) {
                            ous.write(buff, 0, len);
                            ous.flush();
                        }
                        ous.close();
                        Log.i("test", "下载成功");

                        //测试,将下载的图片取出,设置到界面上
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Bitmap bmp = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + "/123.jpg");
                                ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bmp);
                            }
                        });
                    }
                });
            }
        });

五、为ImageView加载图片

        //加载图片
        findViewById(R.id.loadImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpClient mOkHttpClient = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url("http://b.hiphotos.baidu.com/image/pic/item/0b55b319ebc4b7455203681bcdfc1e178a821523.jpg")
                        .build();
                //new call
                Call call = mOkHttpClient.newCall(request);


                //请求加入调度
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        Log.i("test", "fail");
                    }

                    @Override
                    public void onResponse(final Response response) throws IOException {
                        //希望获得返回的字符串,可以通过response.body().string()获取
                        //如果希望获得返回的二进制字节数组,则调用response.body().bytes()
                        //想拿到返回的inputStream,则调用response.body().byteStream()
                        if (!response.isSuccessful()) {
                            Log.i("test", "response is not success");
                        }
                        InputStream ins = response.body().byteStream();
                        final Bitmap bmp = BitmapFactory.decodeStream(ins);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bmp);
                            }
                        });


                    }
                });
            }
        });

    }
}


源代码和  上传文件的服务端代码后续给出




猜你喜欢

转载自blog.csdn.net/qq_34763699/article/details/60570625