Android

OkGo网络框架的用法

2018-04-02  本文已影响208人  名字_都被占了

首先添加如下依赖:

compile 'com.lzy.net:okgo:3.0.4'

先在application中初始化

OkGo.getInstance().init(this);

MainActivity.java文件中

public class EasyHttpActivity extends AppCompatActivity {
    private ImageView imageView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.easyhttpactivity);
        checkSDCardPermission();
        imageView= (ImageView) findViewById(R.id.image);
    }

    //get请求
    public void getQingQiu(View view) {//这个方法要在xml文件的onClick属性中出现,所以方法必须是public的才行,不能是private
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkGo.<String>get("http://39.107.104.102:8080/gundongyemianwangzhi.jsp")
                        .cacheKey("diyi")//要缓冲的那个类型必须实现Serializable接口才行,并且如果其他地方出现一样的cacheKey,就会顶替掉原先的cacheKey对应的值。
                        .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Log.d("EasyHttpActivity", "response:"+response.body() );
                            }
                        });
            }
          /*  输出结果为:
            04-02 15:13:42.080 5086-5086/com.example.liang.lianxi D/EasyHttpActivity: response:[{"imagename":"tu1","imagesrc":"http://touch.xueersi.com/chu1-0-4"},{"imagename":"tu2","imagesrc":"http://zt.xueersi.com/2018dzj/touch.html"},{"imagename":"tu3","imagesrc":"http://touch.xueersi.com/chu3-0-4"},{"imagename":"tu4","imagesrc":"http://touch.xueersi.com/lecture/lectureSeriesList/82"},
            {"imagename":"tu5","imagesrc":"http://zt.xueersi.com/2018jszbs/"}]*/
        }).start();

    }
//post请求
    public void postQingQiu(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkGo.<String>post("http://39.107.104.102:8080/getschool.jsp").params("get","18435997685")
                        .cacheKey("tupian")//要缓冲的那个类型必须实现Serializable接口才行
                        .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                        .execute(new AbsCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.d("EasyHttpActivity", "response:"+response.headers().get("Set-Cookie") );
                    }

                    @Override
                    public String convertResponse(okhttp3.Response response) throws Throwable {//只有先在这个方法里面处理了数据,返回之后,onSuccess方法中才能收到数据,并且缓冲中保存的也是这里返回的数据
                        Log.d("EasyHttpActivityfdfdf", response.header("Set-Cookie"));
                        return response.header("Set-Cookie");
                    }
                });
       /* 输出结果为:
        04-02 14:59:00.350 5086-9330/com.example.liang.lianxi D/EasyHttpActivityfdfdf: school=运城学院
        04-02 14:59:00.350 5086-5086/com.example.liang.lianxi D/EasyHttpActivity: response:school=运城学院*/
            }
        }).start();
    }
//获取图片的请求
    public void bitmapQingQiu(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkGo.<Bitmap>get("http://39.107.104.102:8080/downloadtouxiang.jsp").headers("user","18435997685")
                        //这里用post也能获取到图片,应该和服务器端的代码有关
                        .execute(new BitmapCallback() {
                            @Override
                            public void onSuccess(Response<Bitmap> response) {
                                imageView.setImageBitmap(response.body());
                            }
                        });
            }
        }).start();
    }
//读取网络缓冲
    public void duQuHuanChong(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<CacheEntity<?>> list=CacheManager.getInstance().getAll();
                Log.d("EasyHttpActivity", "list.size():" + list.size());
                Log.d("EasyHttpActivity",CacheManager.getInstance().get("tupian").getData().toString());
                Log.d("EasyHttpActivity",CacheManager.getInstance().get("diyi").getData().toString());
            }
        }).start();
    }
//代码进度条的文件下载
    public void jindutiao(View view){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkGo.<File>get("http://39.107.104.102:8080/downloadkejian.jsp").headers("user","18435997685_02-18-22:55:31_03-03-16:09:57.pdf")
                        .execute(new FileCallback("kejian.pdf") {//在下载中,可以设置下载下来的文件的名字
                            @Override
                            public void downloadProgress(Progress progress) {
                                super.downloadProgress(progress);
                                Log.d("EasyHttpActivity", "当前下载了:"+progress.currentSize + ",总共有:" + progress.totalSize+",下载速度为:"+progress.speed);//这个totalSize一直是初始值-1,很尴尬
                                Log.d("xinxi", progress.toString());
                            }

                            @Override
                            public void onSuccess(Response<File> response) {
                                Log.d("EasyHttpActivity", "下载完成");
                            }
                        });
            }
        }).start();
    }
//代码进度条的文件上传
    public void shangchuanjindutiao(View view){
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<File>list=new ArrayList<>();
                list.add(new File("/storage/emulated/0/2.mp3"));
                OkGo.<File>post("http://39.107.104.102:8080/uploadkejian.jsp").addFileParams("zhi",list)
                        .execute(new FileCallback() {
                            @Override
                            public void uploadProgress(Progress progress) {
                                super.uploadProgress(progress);
                                Log.d("EasyHttpActivity", progress.toString());
                            }

                            @Override
                            public void onSuccess(Response<File> response) {
                                Log.d("EasyHttpActivity", "上传成功");
                            }
                        });
            }
        }).start();
    }

    protected void checkSDCardPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x01);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x01) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //获取权限
            } else {
                Toast.makeText(this, "权限被禁止,无法下载文件!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

在main_activity.xml文件中

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="getQingQiu"
            android:text="get请求"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="postQingQiu"
            android:text="post请求"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="bitmapQingQiu"
            android:text="bitmap请求"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="duQuHuanChong"
            android:text="读取缓存"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="jindutiao"
            android:text="带有进度条的下载"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="shangchuanjindutiao"
            android:text="带有进度条的上传"/>


        <ImageView
            android:id="@+id/image"
            android:layout_width="300dp"
            android:layout_height="300dp"/>
    </LinearLayout>
</ScrollView>
参考文章如下

https://www.jianshu.com/p/6aa5cb272514

上一篇下一篇

猜你喜欢

热点阅读