Android Studio 2 -2 okhttp单例封装

Android Studio 2 -1 okhttp单例封装

model

接口

package com.example.okhttp_util.inter;

public interface MyHttpInter {
    void onOk(String json);
    void onERROR(String msg);
}

接口

package com.example.okhttp_util.model;

import com.example.okhttp_util.inter.MyHttpInter;

import java.util.HashMap;

public interface HomeModel {
    void getbanner(String postURL, HashMap<String,String> hashMap, MyHttpInter inter);
}

实现类

package com.example.okhttp_util.model;

import com.example.okhttp_util.inter.MyHttpInter;
import com.example.okhttp_util.util.OkHttpUtil;

import java.util.HashMap;

public class HomeModelImpl implements HomeModel{
    @Override
    public void getbanner(String postURL, HashMap<String,String> hashMap, MyHttpInter inter) {
        OkHttpUtil.getInstance().doPost(postURL, hashMap, inter);
    }
}

主代码

package com.example.okhttp_util;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.okhttp_util.inter.MyFileInter;
import com.example.okhttp_util.inter.MyHttpInter;
import com.example.okhttp_util.inter.MyProgressinter;
import com.example.okhttp_util.model.HomeModel;
import com.example.okhttp_util.model.HomeModelImpl;
import com.example.okhttp_util.util.OkHttpUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "jsy";

    private Button btnGet;
    private Button btnPost;
    private Button btnUploading;
    private Button btnDownloading;

    private SeekBar seekBar;
    private int zhi;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };

    private HomeModel homeModel;

    private String getURL = "http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app";
    private String postURL = "http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app";
    private String mp4URL = "http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4";

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

        homeModel = new HomeModelImpl();

        btnGet = (Button) findViewById(R.id.btn_get1);
        btnPost = (Button) findViewById(R.id.btn_post1);
        btnUploading = (Button) findViewById(R.id.btn_uploading1);
        btnDownloading = (Button) findViewById(R.id.btn_downloading1);

        btnGet.setOnClickListener(this);
        btnPost.setOnClickListener(this);
        btnUploading.setOnClickListener(this);
        btnDownloading.setOnClickListener(this);

        seekBar = findViewById(R.id.seek);
        seekBar.setVisibility(View.GONE);
        seekBar.setProgress(zhi);

        String[] permission = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(permission, 8848);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 8848 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
//            Toast.makeText(this, "必须同意", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_get1:
                Log.i(TAG, "onClick: -0----------get");
                get();
                break;
            case R.id.btn_post1:
                Log.i(TAG, "onClick: -0----------post");
                post();
                break;
            case R.id.btn_uploading1:
                Log.i(TAG, "onClick: -0----------up");
                try {
                    upload();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_downloading1:
                Log.i(TAG, "onClick: -0----------down");
                down();
                break;
            default:
        }

    }

    private void upload() throws IOException {

        OkHttpUtil.getInstance().doUpload("http://169.254.142.167/hfs", "/sdcard/Music/Ice Paper - 心如止水.flac", "King.mp3", "media/mp3", new MyFileInter() {
            @Override
            public void onError(String msg) {
                Log.i(TAG, "onError: "+msg);
            }

            @Override
            public void onFinish() {
                Log.i(TAG, "onFinish: ");
            }
        });

//        OkHttpClient client = new OkHttpClient.Builder()
//                .callTimeout(5, TimeUnit.SECONDS)
//                .readTimeout(5, TimeUnit.SECONDS)
//                .build();
//
//        //上传文件的请求体
//        MultipartBody requestBody = new MultipartBody.Builder()
//                .setType(MultipartBody.FORM)
//                // 服务器端的名字
//                .addFormDataPart("file", "JinSiYu.mp3",
//                        RequestBody.create(MediaType.parse("Media/mp3"), new File("/sdcard/Music/Ice Paper - 心如止水.flac")))
//                .build();
//
//        //142.167 自己
//        //113.244 讲师
//        final Request request = new Request.Builder()
//                .url("http://169.254.142.167/hfs")
//                .post(requestBody)//post提交必须要设置请求体
//                .build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//            }
//        });


    }


    private void down() {

        OkHttpUtil.getInstance().doDownload(mp4URL, "/sdcard/Movies/asd.mp4", new MyProgressinter() {
            @Override
            public void onERROR(String msg) {
                Log.i(TAG, "onERROR: "+msg);
            }

            @Override
            public void onFinish() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setVisibility(View.GONE);
                    }
                });
                Log.i(TAG, "onFinish: ");
            }

            @Override
            public void onProgress(final int position) {
               handler.post(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setVisibility(View.VISIBLE);
                        seekBar.setProgress(position);
                    }
                });
                Log.i(TAG, "onProgress: "+position);
            }
        });

//        //创建对象 设置属性
//        OkHttpClient client = new OkHttpClient.Builder()
//                .callTimeout(1, TimeUnit.MINUTES)
//                .readTimeout(1, TimeUnit.MINUTES)
//                .build();
//
//        //Request对象
//        Request request = new Request.Builder()
//                .url(mp4URL)
//                .get()
//                .build();
//
//        //客户端发送请求
//        Call call = client.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                ResponseBody body = response.body();
//
//                long l = body.contentLength();//总长度
//                Log.i(TAG, "onResponse: 总大小" + l);
//
//                seekBar.setMax((int) l);
//
//                InputStream inputStream = body.byteStream();
//                FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/Movies/asd.mp4");
//                byte[] bytes = new byte[2048];
//                int len = 0;
//                zhi = 0;//进度
//
//                while ((len = inputStream.read(bytes)) != -1) {
//                    zhi += len;
//
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//
//                            seekBar.setProgress(zhi);
//                        }
//                    });
//
//                    fileOutputStream.write(bytes, 0, len);
//                    Log.i(TAG, "onResponse: " + zhi);
//                }
//
//
//            }
//        });


    }

    private void post() {

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("itemid", "2");
        hashMap.put("act", "ad_app");
        homeModel.getbanner(postURL, hashMap, new MyHttpInter() {
            @Override
            public void onOk(String json) {
                Log.i(TAG, "onOk: "+json);
            }

            @Override
            public void onERROR(String msg) {
                Log.i(TAG, "onERROR: "+msg);
            }
        });

//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("itemid", "2");
//        hashMap.put("act", "ad_app");
//
//        OkHttpUtil.getInstance().doPost(postURL,hashMap);

//        //创建对象 设置属性
//        OkHttpClient client = new OkHttpClient.Builder()
//                .callTimeout(1, TimeUnit.MINUTES)
//                .readTimeout(1, TimeUnit.MINUTES)
//                .build();
//
//        //itemid=2&act=ad_app
//        FormBody formBody = new FormBody.Builder()
//                .add("itemid", "2")
//                .add("act", "ad_app")
//                .build();
//        //Request对象
//        Request request = new Request.Builder()
//                .url(postURL)
//                .post(formBody)
//                .build();
//
//        //客户端发送请求
//        Call call = client.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i(TAG, "onFailure: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                //注意单词不一样
//                ResponseBody body = response.body();
//                //特别注意  body.string()  只可以被调用一次 是IO流的管道 输出后就空了
//                String json = body.string();
//                Log.i(TAG, "onResponse: " + json);
//            }
//        });

    }

    private void get() {

        OkHttpUtil.getInstance().doGet(getURL, new MyHttpInter() {
            @Override
            public void onOk(String json) {
                Log.i(TAG, "onOk: "+json);
            }

            @Override
            public void onERROR(String msg) {
                Log.i(TAG, "onERROR: "+msg);
            }
        });

//        //创建对象 设置属性
//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        builder.readTimeout(1, TimeUnit.MINUTES);
//        builder.callTimeout(1, TimeUnit.MINUTES);
//        OkHttpClient client = builder.build();
//
//        //Request对象
//        Request.Builder builder1 = new Request.Builder();
//        builder1.url(getURL);
//        builder1.get();
//        final Request request = builder1.build();
//
//        //客户端发送请求
//        Call call = client.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i(TAG, "onFailure: " + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                //注意单词不一样
//                ResponseBody body = response.body();
//                String json = body.string();
//                Log.i(TAG, "onResponse: " + json);
//            }
//        });

    }


}

发布了20 篇原创文章 · 获赞 4 · 访问量 897

猜你喜欢

转载自blog.csdn.net/v1141261428/article/details/100187700