Okgo的使用,和简单的再封装

Okgo的使用,和简单的再封装

    • OkGO de 基本使用
    • OkGo 简单的再封装

OkGO de 基本使用

首先导入依赖/-----implementation ‘com.lzy.net:okgo:3.0.4’

以上传文件 /下载文件/下载Bitmap为例:

布局xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击上传"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击下载"/>
    <ProgressBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击下载图片"/>
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</LinearLayout>

java代码

package com.example.day1105_topic4;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button1;
    private Button button2;
    private ProgressBar bar;
    private Button button3;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        initView();
    }

    private void initView() {
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        bar = (ProgressBar) findViewById(R.id.bar);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3 = (Button) findViewById(R.id.button3);
        button3.setOnClickListener(this);
        iv = (ImageView) findViewById(R.id.iv);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1: // 上传
                OkGo.<String>post("http://169.254.153.138/hfs/")
                        .isMultipart(true)
                        .params("file", new File("/storage/emulated/0/happy.mp4"), "000.mp4")
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                Toast.makeText(MainActivity.this, "" + response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void uploadProgress(Progress progress) {
                                super.uploadProgress(progress);
                                bar.setProgress((int) (progress.fraction * 100));
                            }
                        });

                break;
            case R.id.button2: // 下载
                OkGo.<File>get("http://169.254.153.138/hfs/happy.mp4")
                        .execute(new FileCallback("/storage/emulated/0", "live.mp4") {
                            @Override
                            public void onSuccess(Response<File> response) {
                                Toast.makeText(MainActivity.this, "下载成功!", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(Response<File> response) {
                                super.onError(response);
                                Toast.makeText(MainActivity.this, "" + response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void downloadProgress(Progress progress) {
                                super.downloadProgress(progress);
                                bar.setProgress((int) (progress.fraction * 100));
                            }
                        });
                break;
            case R.id.button3: // 点击下载图片
                OkGo.<Bitmap>get("http://169.254.153.138/hfs/xiaoming.jpg")
                        .execute(new BitmapCallback() {
                            @Override
                            public void onSuccess(Response<Bitmap> response) {
                                iv.setImageBitmap(response.body());
                            }
                        });
                break;
        }
    }
}

OkGo 简单的再封装

以直接获取json解析后的对象 或 数组为例

1.创建bean类(省略)
2.创建abstract抽象类JsonCallBack
3.new JsonCallBack获取数据

JsonCallBack代码

package com.example.app_callback.callback;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.callback.AbsCallback;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 自定义的CallBack
 * 完成 直接或去对象 或者 数组的功能
 * @param 
 */
public abstract class JsonCallBack<T> extends AbsCallback<T> {
    private Class<T> tClass; // 对应的class 对象

    public JsonCallBack(Class<T> tClass) {
        this.tClass = tClass;
    }

    @Override
    public T convertResponse(Response response) throws Throwable {
        ResponseBody body = response.body();
        // 加入两个 非空 判断
        if(body == null){
            return null;
        }
        if (tClass == null){
            return null;
        }
        String json = body.string();
        T t = JSON.parseObject(json, tClass); // 解析 返回 指定类型数据
        return t;
    }
}

MainActivity代码

package com.example.app_callback;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.app_callback.bean.Bean;
import com.example.app_callback.callback.JsonCallBack;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button_jsonCallBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        button_jsonCallBack = (Button) findViewById(R.id.button_jsonCallBack);

        button_jsonCallBack.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_jsonCallBack:
                OkGo.[]>get("http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app")
                        .execute(new JsonCallBack<Bean[]>(Bean[].class) {
                            @Override
                            public void onSuccess(Response<Bean[]> response) {
                                Bean[] body = response.body();
                                Toast.makeText(MainActivity.this, ""+body[0], Toast.LENGTH_SHORT).show();
                            }
                        });
                break;
        }
    }
}

你可能感兴趣的:(Okgo的使用,和简单的再封装)