第二单元MVC模式

DAY2.MVC模式

一:MVC的意思
二:MVC的优点
三:实现MVC模式
1.MVC的介绍

MVC:Model-View-Controller

Model:模型层业务数据的信息的表示,关注支撑业务的信息构成,通常是多个业务实体的组合,如Course类(包含id,title)

View:视图层(为用户提供UI,重点关注数据呈现)

Controller:连接View和Model,调用业务逻辑产生合适的数据(Model),传递数据给视图层用于呈现

2.MVC的优点

1、MVC是一种架构模式,程序分层,分工合作,相互独立又协同工作。

(1)程序分层,分工合作:MVC将程序分成三层:模型层,视图层,控制层,有了程序的分工合作,程序员就有了工种的分离(前端工程师和后端工程师/后端逻辑开发和前端页面开发)

(2)相互独立,协同工作:如在前端控制器的图中,Controller和Viewer并不耦合,之间可以没有任何联系,但是需要根据页面的要求产生合适的数据,而页面呈现又不能脱离业务逻辑凭空展开一定是基于业务逻辑的,所以它们之间是即相互独立又协同工作的。

2、MVC是一种思考方式?

前面通过MVC将程序分层了,分成了模型层,视图层,控制器层,那么就需要在这个层面上进行思考,在模型层上去思考将给用户展示什么信息来构成模型,在视图层需要考虑如何将这些数据布局,怎么以更加优美合理的方式展现给用户,控制器层需要考虑调用哪些业务逻辑,使得我们可以呈现给用户正确的数据,效率更高,性能更好。

3.实现MVC
public interface MyFileListener {
    void setMax(int max);
    void setProgress(int progress);
    void onFinish();
    void onError(String message);
}
public interface MyOklistener {
    void onOk(String json);
    void onError(String message);
}
public interface OkHttpModel {
    void get(String str_url, MyOklistener listener);
}

package com.example.day02.util;

import android.util.Log;

import com.example.day02.listener.MyFileListener;
import com.example.day02.listener.MyOklistener;
import com.example.day02.listener.MyProgressListener;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpUtil {
    private OkHttpClient okHttpClient;
    private HttpUtil(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("shk", "wohaoshuai: "+message);

            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor token = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().header("token", "abcabcabc8").build();
                return chain.proceed(request);
            }
        };
        okHttpClient=new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60,TimeUnit.SECONDS)
                .addInterceptor(token)
                .addInterceptor(httpLoggingInterceptor)
                .build();
    }
    private static  HttpUtil httpUtil= null;
    public  static  HttpUtil getInstance(){
        if (httpUtil == null){
            synchronized (Object.class){
                if (httpUtil== null){
                    httpUtil = new HttpUtil();
                }
            }
        }
        return httpUtil;
    }
    public void doget(String url, final MyOklistener listener){
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onOk(response.body().string());
            }
        });

    }
    public void dopost(String url, HashMap<String,String> map, final MyOklistener listener){
        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            builder.add(key,value);
        }
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onOk(response.body().string());
            }
        });
    }
    public void download(String url, final String path, final MyProgressListener listener){
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                long max = body.contentLength();
                InputStream inputStream = body.byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                byte[] bytes=new byte[1024];
                int len=0;
                int count=0;
                while ((len=inputStream.read(bytes))!=-1){
                    count+=len;
                    fileOutputStream.write(bytes,0,len);
                    listener.onProgress((int) (count*100/max));
                }
                if(count>=max){
                    listener.onFinish();
                }
            }
        });

    }
    public void upload(String str_url, String path, String filename, String type, final MyFileListener listener){
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", filename, RequestBody.create(MediaType.parse(type), new File(path)))
                .build();
        Request request = new Request.Builder().url(str_url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onFinish();
            }
        });
    }
}

package com.example.day02;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;

import com.example.day02.listener.MyOklistener;
import com.example.day02.listener.MyProgressListener;
import com.example.day02.util.HttpUtil;

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.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {
    private Button get;
    private Button post;
    private Button load;
    private Button unload;
    private ProgressBar progressBar;
    String get_url="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&itemid=2&act=ad_app";
    String post_url="http://api.yunzhancn.cn/api/app.interface.php?siteid=78703&";
    String download_url="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);
        progressBar = findViewById(R.id.pb);
        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);
        load = (Button) findViewById(R.id.load);
        unload = (Button) findViewById(R.id.unload);

        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                OkHttpClient.Builder builder = new OkHttpClient.Builder();
//                builder.readTimeout(1, TimeUnit.MINUTES);
//                builder.connectTimeout(1,TimeUnit.MINUTES);
//                OkHttpClient client = builder.build();
//
//                Request.Builder builder1 = new Request.Builder();
//                builder1.url(get_url);
//                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);
//
//
//                    }
//                });
                HttpUtil.getInstance().doget(get_url, new MyOklistener() {
                    @Override
                    public void onOk(String json) {
                        Log.i("TAG", "onOk: "+json);
                    }

                    @Override
                    public void onError(String message) {
                        Log.i("TAG", "onError: "+message);
                    }
                });
            }
        });
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                OkHttpClient client = new OkHttpClient.Builder()
//                        .readTimeout(1, TimeUnit.MINUTES)
//                        .callTimeout(1, TimeUnit.MINUTES)
//                        .build();
//
//                FormBody formBody = new FormBody.Builder()
//                        .add("itemid", "2")
//                        .add("act", "ad_app")
//                        .build();
//                Request request = new Request.Builder()
//                        .url(post_url)
//                        .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();
//                        Log.i("TAG", "onResponse: "+body.string());
//                    }
//                });

                HashMap<String, String> map = new HashMap<>();
                map.put("itemid","2");
                map.put("act","ad_app");
                HttpUtil.getInstance().dopost(post_url,map, new MyOklistener() {
                    @Override
                    public void onOk(String json) {
                        Log.i("TAG", "onOk: "+json);
                    }

                    @Override
                    public void onError(String message) {
                        Log.i("TAG", "onError: "+message);

            }
             });
            }
        });
        unload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkHttpClient client = new OkHttpClient.Builder()
                        .readTimeout(1, TimeUnit.MINUTES)
                        .callTimeout(1, TimeUnit.MINUTES)
                        .build();
                RequestBody requestBody = RequestBody.create(MediaType.parse("media/map4"), new File("/sdcard/Movies/hz.mp4"));
                MultipartBody body = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file","shk.mp4",requestBody)
                        .build();
                Request request = new Request.Builder()
                        .url("http://169.254.218.199/hfs/")
                        .post(body)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("TAG", "onFailure: 上传失败 ");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("TAG", "onResponse:上传成功 ");
                    }
                });


            }
        });
        load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                OkHttpClient client = new OkHttpClient.Builder()
//                        .readTimeout(1, TimeUnit.MINUTES)
//                        .callTimeout(1, TimeUnit.MINUTES)
//                        .build();
//                Request request = new Request.Builder()
//                        .url(download_url)
//                        .get()
//                        .build();
//                Call call = client.newCall(request);
//                call.enqueue(new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        Log.i("TAG", "onFailure: ");
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        ResponseBody body = response.body();
//                        long l = body.contentLength();
//                        Log.i("TAG", "onResponse:总大小 "+l);
//                        InputStream inputStream = body.byteStream();
//                        FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/Movies/hz.mp4");
//                        byte[] bytes = new byte[1024];
//                        progressBar.setMax(100);
//                        int len = 0;
//                        int count= 0;
//                        while((len=inputStream.read(bytes))!=-1){
//                            count+=len;
//                            fileOutputStream.write(bytes,0,len);
//                            progressBar.setProgress(count);
//                            Log.i("TAG", "onResponse:当前进度 "+count);
//                        }
//                    }
//                });
                HttpUtil.getInstance().download(download_url, "/sdcard/Movies/shk.mp4", new MyProgressListener() {
                    @Override
                    public void onError(String message) {
                        Log.i("TAG", "onError: "+message);
                    }

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

                    @Override
                    public void onProgress(int progress) {
                        Log.i("TAG", "onProgress: "+progress);
                    }
                });

            }
        });

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值