Android上传Github

点击有爆款哦~~

package com.dabao.retrofitmvpdemo.api;

/**
 * Created by mypc on 2018/3/30.
 */

public class APIs {

//    public static String debugApi="http://test.sipaote.cn/qinglong/delivery/ass/";   //   线上测试  175.25.17.52

    public static String debugApi="https://api.tianapi.com/";

    // https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1
    public static String wxnew="wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=1";

    public static String  MeiTuan="v2/epassport/logon";

}
package com.dabao.retrofitmvpdemo.retrofit;

import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Url;

/**
 *
 * Created by liqy on 2018/1/28.
 *
 */

public interface SearchApi {

    /**
     *  普通get请求
     * @param url
     * @return
     */
    @GET
    Observable get(@Url String url);

    /**
     *  普通post请求
     * @return
     */
    @FormUrlEncoded
    @POST
    Observable post(@Url String url, @FieldMap Map map);

    /**
     *  retrofit+Rxjava的图形获取与转换  get获取图片
     * @param fileUrl
     * @return
     */
    @GET
    Observable downloadPicFromNet_Get(@Url String fileUrl);


    /**
     * retrofit以json形式入参 的 post请求
     * @param url
     * @param route
     * @return
     */
//    这里可以用注解的形式添加请求头
//    @Headers({
//            "Content-Type:application/x-www-form-urlencoded",
//            "Referer:http://e.waimai.meituan.com/v2/epassport/entry?BSID=wFLZPV9qAS9Gwzx6RnfB3QzIMKb-kQ0sN0uc0OtTTuoszWlnO6FF6_Y7Q8GBpd9lyJx1lqFu6QVurCjTCemOZA",
//            "X-Requested-With:XMLHttpRequest",
//            "User-Agent:MeituanWaimai/ai/3.0.1.0/32 Win Windows/6.3",
//    })
    @POST
    Observable postFlyRoute(@Url String url,@Body RequestBody route);//传入的参数为RequestBody


    /**
     * 多文件上传
     * @param photos
     * @return
     *
     * @Part() 可以添加普通参数 没有就不加
     */
    @Multipart
    @POST("qinglong/shop/picture/approve")
    Observable uploadFile(@Part() List photos);

}
package com.dabao.retrofitmvpdemo.retrofit;

import android.support.annotation.NonNull;

import com.dabao.retrofitmvpdemo.api.APIs;
import com.dabao.retrofitmvpdemo.appliction.DashApplication;
import com.dabao.retrofitmvpdemo.util.LogUtils;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by mypc on 2018/1/5.
 *
 * http://www.yulin520.com/
 */

public class RetrofitFacety {

    //使全局就一个OKHttpClient对象
    public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new ApplictionInterceptor())  // 添加公共参数拦截器
            .addInterceptor(DashApplication.loggingInterceptor)  // 添加retrofit日志拦截器
            .cookieJar(new CookieManger(DashApplication.getAppContext()))  //传递cookie  保持后台的sessionid
            .connectTimeout(50, TimeUnit.SECONDS)
            .readTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .build();

    //使全局就一个Retrofit对象,设置基础Url
    public static SearchApi apiService = new Retrofit.Builder()
            .baseUrl(APIs.debugApi)
            //使我们能高度自定义转化器
            .addConverterFactory(ScalarsConverterFactory.create())
            .client(okHttpClient)
            //把 以前的 call 转化成 Observable,这是Retrofit与RxJava结合使用的关键
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(SearchApi.class);


    /**
     *  retrofit的get请求
     * @param url
     * @return
     */
    public static Observable get(final String url) {

        return apiService.get(url)
                .doOnNext(new Consumer() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
//                        LogUtils.i("wc",url+"===get===这是处理缓存本地操作==="+s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     *  json格式入参 retrofit的post请求
     * @param url
     * @param map
     * @return
     *
     *  取消请求
     */
    public static Observable postFlyRoute(final String url, Map map){

        String route = new Gson().toJson(map);
        //3、将json对象转化为json字符串
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);

        return apiService.postFlyRoute(url,body)
                .doOnNext(new Consumer() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
//                        LogUtils.i("wc",url+"==post===这是个什么==="+s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

    }

    /**
     * retrofit的普通post请求
     * @param url
     * @param map
     * @return
     *
     *  取消请求
     */
    public static Observable post(final String url, Map map){

        return apiService.post(url,map)
                .doOnNext(new Consumer() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
//                        LogUtils.i("wc",url+"==post===这是个什么==="+s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    /**
     * 获取图形验证码
     * @param url
     * @return
     */
    public static Observable get_img(final String url){

        return apiService.downloadPicFromNet_Get(url)
                .doOnNext(new Consumer() {
                    @Override
                    public void accept(@NonNull ResponseBody s) throws Exception {
//                        LogUtils.i("wc",url+"==get===获取图形验证码==="+s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    //参数拦截器
    public static class ApplictionInterceptor implements Interceptor {

     @Override
     public Response intercept(Chain chain) throws IOException {
         //获取到请求
         Request original = chain.request();
         //获取请求的方式
         String method = original.method();
         //获取请求的路径
         String oldUrl = original.url().toString();
         LogUtils.i("jba","拦截器==="+original.url()+"---"+original.method()+"--"+original.header("User-agent"));

         if ("POST".equals(method)){
             Request build = original.newBuilder()
                     .header("token","wx_login_24_f8695dca3874362662824a6f41d33c2bba84d3025a910a4c54bd8cdeeabd5c5f")
                     .header("os", "Android")
                     .header("platform", "App")
                     .header("version", "2.0.0")
                     .header("device","0716f5e91daad18b")
                     .method(method, original.body())
                     .url(oldUrl)
                     .build();

             Response response = chain.proceed(build);

             return response;
         }

         return null;
     }
 }

}
package com.dabao.retrofitmvpdemo.retrofit;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by zzt on 2018/5/30.
 */

public class PersistentCookieStore {
    private static final String LOG_TAG = "PersistentCookieStore";
    private static final String COOKIE_PREFS = "Cookies_Prefs";

    private final Map> cookies;
    private final SharedPreferences cookiePrefs;


    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<>();

        //将持久化的cookies缓存到内存中 即map cookies
        Map prefsMap = cookiePrefs.getAll();
        for (Map.Entry entry : prefsMap.entrySet()) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        if (!cookies.containsKey(entry.getKey())) {
                            cookies.put(entry.getKey(), new ConcurrentHashMap());
                        }
                        cookies.get(entry.getKey()).put(name, decodedCookie);
                    }
                }
            }
        }
    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }

    public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        //将cookies缓存到内存中 如果缓存过期 就重置此cookie
        if (!cookie.persistent()) {
            if (!cookies.containsKey(url.host())) {
                cookies.put(url.host(), new ConcurrentHashMap());
            }
            cookies.get(url.host()).put(name, cookie);
        } else {
            if (cookies.containsKey(url.host())) {
                cookies.get(url.host()).remove(name);
            }
        }

        //讲cookies持久化到本地
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
        prefsWriter.putString(name, encodeCookie(new OkHttpCookies(cookie)));
        prefsWriter.apply();
    }

    public List get(HttpUrl url) {
        ArrayList ret = new ArrayList<>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());
        return ret;
    }

    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        cookies.clear();
        return true;
    }

    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
            cookies.get(url.host()).remove(name);

            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if (cookiePrefs.contains(name)) {
                prefsWriter.remove(name);
            }
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.apply();

            return true;
        } else {
            return false;
        }
    }

    public List getCookies() {
        ArrayList ret = new ArrayList<>();
        for (String key : cookies.keySet())
            ret.addAll(cookies.get(key).values());

        return ret;
    }

    /**
     * cookies 序列化成 string
     *
     * @param cookie 要序列化的cookie
     * @return 序列化之后的string
     */
    protected String encodeCookie(OkHttpCookies cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in encodeCookie", e);
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    /**
     * 将字符串反序列化成cookies
     *
     * @param cookieString cookies string
     * @return cookie object
     */
    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((OkHttpCookies) objectInputStream.readObject()).getCookies();
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in decodeCookie", e);
        } catch (ClassNotFoundException e) {
            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
        }

        return cookie;
    }

    /**
     * 二进制数组转十六进制字符串
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * 十六进制字符串转二进制数组
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}
package com.dabao.retrofitmvpdemo.retrofit;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import okhttp3.Cookie;

/**
 * Created by zzt on 2018/5/30.
 */

public class OkHttpCookies implements Serializable{
    private transient final Cookie cookies;
    private transient Cookie clientCookies;

    public OkHttpCookies(Cookie cookies) {
        this.cookies = cookies;
    }

    public Cookie getCookies() {
        Cookie bestCookies = cookies;
        if (clientCookies != null) {
            bestCookies = clientCookies;
        }
        return bestCookies;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(cookies.name());
        out.writeObject(cookies.value());
        out.writeLong(cookies.expiresAt());
        out.writeObject(cookies.domain());
        out.writeObject(cookies.path());
        out.writeBoolean(cookies.secure());
        out.writeBoolean(cookies.httpOnly());
        out.writeBoolean(cookies.hostOnly());
        out.writeBoolean(cookies.persistent());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        String name = (String) in.readObject();
        String value = (String) in.readObject();
        long expiresAt = in.readLong();
        String domain = (String) in.readObject();
        String path = (String) in.readObject();
        boolean secure = in.readBoolean();
        boolean httpOnly = in.readBoolean();
        boolean hostOnly = in.readBoolean();
        boolean persistent = in.readBoolean();
        Cookie.Builder builder = new Cookie.Builder();
        builder = builder.name(name);
        builder = builder.value(value);
        builder = builder.expiresAt(expiresAt);
        builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
        builder = builder.path(path);
        builder = secure ? builder.secure() : builder;
        builder = httpOnly ? builder.httpOnly() : builder;
        clientCookies = builder.build();
    }
}
package com.dabao.retrofitmvpdemo.retrofit;

import android.content.Context;

import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Created by zzt on 2018/5/30.
 */

public class CookieManger implements CookieJar {

    private static Context mContext;

    private static PersistentCookieStore cookieStore;

    public CookieManger(Context context) {
        mContext = context;
        if (cookieStore == null ) {
            cookieStore = new PersistentCookieStore(mContext);
        }

    }

    @Override
    public void saveFromResponse(HttpUrl url, List cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
            }
        }
    }

    @Override
    public List loadForRequest(HttpUrl url) {
        List cookies =cookieStore.get(url);
        return cookies;
    }
}
package com.dabao.retrofitmvpdemo.retrofit;


import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by mypc on 2018/1/6.
 *
 * 子类的共有方法
 */

public abstract class BaseServer implements Observer {

    public abstract void onSuccess(String myBean);
    public abstract void onErroy(String ss);

    @Override
    public void onError(Throwable e) {
        onErroy("请求失败");
    }

    @Override
    public void onNext(String myBean) {
        onSuccess(myBean);
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onComplete() {

    }
}
package com.dabao.retrofitmvpdemo.retrofit;

/**
 * Created by mypc on 2018/1/28.
 *
 * 正常数据的回传 string
 */

public interface MyInterfaces {
    void chenggong(String json);
    void shibai(String ss);
}
package com.dabao.retrofitmvpdemo.retrofit;

import android.graphics.Bitmap;

/**
 * Created by zzt on 2018/6/6.
 *
 * 用于回调图片
 */

public interface MyJieKou {
    void chenggong(Bitmap bitmap);
    void shibai(String ss);
}
package com.dabao.retrofitmvpdemo.model;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.dabao.retrofitmvpdemo.retrofit.BaseServer;
import com.dabao.retrofitmvpdemo.retrofit.MyInterfaces;
import com.dabao.retrofitmvpdemo.retrofit.MyJieKou;
import com.dabao.retrofitmvpdemo.retrofit.RetrofitFacety;

import java.io.InputStream;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Created by mypc on 2018/1/10.
 *
 * model层里,我做了retrofit+RxJava的封装处理,这里就不再展示代码了,向看代码可以到我的博客去看!
 *
 * 地址:http://blog.csdn.net/weixin_40430041/article/details/78988137
 */

public class MyModel {


    /**
     * model中的普通get请求方式
     * @param url
     * @param myInterfaces
     */
    public void getModContent(final String url, final MyInterfaces myInterfaces){
        RetrofitFacety.get(url)
                .subscribe(new BaseServer() {
                    @Override
                    public void onSuccess(String json) {
                        myInterfaces.chenggong(json);
                    }
                    @Override
                    public void onErroy(String ss) {
                        myInterfaces.shibai(ss);
                    }
                });
    }

    /**
     * model中的普通post请求
     * @param url
     * @param map
     * @param myInterfaces
     */
    public void postModContent(final String url, final Map map, final MyInterfaces myInterfaces){

        RetrofitFacety.post(url,map)
                .subscribe(new BaseServer() {
                    @Override
                    public void onSuccess(String json) {
                        myInterfaces.chenggong(json);
                    }

                    @Override
                    public void onErroy(String ss) {
                        myInterfaces.shibai(ss);
                    }
                });
    }


    /**
     * model中的postFlyRoute请求 添加头参数 且已json格式入参
     * @param url
     * @param map
     * @param myInterfaces
     */
    public void postFlyRouteModContent(final String url, final Map map, final MyInterfaces myInterfaces){

        RetrofitFacety.postFlyRoute(url,map)
                .subscribe(new BaseServer() {
                    @Override
                    public void onSuccess(String json) {
                        myInterfaces.chenggong(json);
                    }

                    @Override
                    public void onErroy(String ss) {
                        myInterfaces.shibai(ss);
                    }
                });
    }


    /**
     *  M 层的获取图形验证码
     * @param url
     * @param myJieKou
     */
    public void getMod_TuXingYanZheng(final String url,final MyJieKou myJieKou){
        RetrofitFacety.get_img(url)
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseBody responseBody) {
                        InputStream inputStream = responseBody.byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        myJieKou.chenggong(bitmap);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        myJieKou.shibai("请求失败!");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
package com.dabao.retrofitmvpdemo.presenter;

import android.graphics.Bitmap;

import com.dabao.retrofitmvpdemo.retrofit.MyInterfaces;
import com.dabao.retrofitmvpdemo.retrofit.MyJieKou;
import com.dabao.retrofitmvpdemo.model.MyModel;

import java.util.Map;


/**
 *
 * @param   v代表view视图
 *
 * p层依然是那么几步操作,
 *    1.p与v的绑定
 *    2.向model层传输url路径,并接收model层回调回来的数据
 *    3.实现p与v的解绑
 */

   //为p层指定泛型对象
public class MyPresenter  {

    private final MyModel myModel;

    V view;

    public MyPresenter() {
        myModel = new MyModel();
    }
    //将p层与v层绑定
    public void attch(V view){
        this.view=view;
    }

    /**
     *  present中的普通get请求
     * @param url
     * @param myInterfaces
     */
    public void getPreContent(String url, final MyInterfaces myInterfaces){
        myModel.getModContent(url, new MyInterfaces() {
            @Override
            public void chenggong(String json) {
                myInterfaces.chenggong(json);
            }

            @Override
            public void shibai(String ss) {
                myInterfaces.shibai(ss);
            }
        });
    }

    /**
     * present中的普通post请求
     * @param url
     * @param map
     * @param myInterfaces
     */
    public void postPreContent(String url, Map map, final MyInterfaces myInterfaces){

        myModel.postModContent(url, map, new MyInterfaces() {
            @Override
            public void chenggong(String json) {
                myInterfaces.chenggong(json);
            }

            @Override
            public void shibai(String ss) {
                myInterfaces.shibai(ss);
            }
        });
    }


    /**
     * present中的postFlyRoute请求  添加头参数 且已json格式入参
     * @param url
     * @param map
     * @param myInterfaces
     */
    public void postFlyRoutePreContent(String url, Map map, final MyInterfaces myInterfaces){

        myModel.postFlyRouteModContent(url, map, new MyInterfaces() {
            @Override
            public void chenggong(String json) {
                myInterfaces.chenggong(json);
            }

            @Override
            public void shibai(String ss) {
                myInterfaces.shibai(ss);
            }
        });
    }

    /**
     *  P 层中的获取图形验证码
     * @param url
     * @param myJieKou
     */
    public void getPro_TuXingYanZheng(String url, final MyJieKou myJieKou){
        myModel.getMod_TuXingYanZheng(url, new MyJieKou() {
            @Override
            public void chenggong(Bitmap bitmap) {
                myJieKou.chenggong(bitmap);
            }

            @Override
            public void shibai(String ss) {
                myJieKou.shibai(ss);
            }
        });
    }




    //将泛型v与p进行解绑
    public void setonDestroy(){
        try{
            this.view=null;
        }catch (Exception e){

        }
    }
}
package com.dabao.retrofitmvpdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dabao.retrofitmvpdemo.api.APIs;
import com.dabao.retrofitmvpdemo.appliction.DashApplication;
import com.dabao.retrofitmvpdemo.base.BaseMVPActivity;
import com.dabao.retrofitmvpdemo.presenter.MyPresenter;
import com.dabao.retrofitmvpdemo.retrofit.BaseServer;
import com.dabao.retrofitmvpdemo.retrofit.MyInterfaces;
import com.dabao.retrofitmvpdemo.util.ImageUtils;
import com.dabao.retrofitmvpdemo.util.LogUtils;
import com.dabao.retrofitmvpdemo.util.MyUtils;
import com.dabao.retrofitmvpdemo.view.ForbidClickListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.dabao.retrofitmvpdemo.retrofit.RetrofitFacety.apiService;
import static com.dabao.retrofitmvpdemo.util.ImageUtils.getPhotos;

public class MainActivity extends BaseMVPActivity>  {

    private Button btn;
    private TextView tv;
    private Button btup;

    @Override
    public MyPresenter initPresenter() {
        if (myPresenter == null) {
            myPresenter = new MyPresenter();
        }
        return myPresenter;
    }

    List photos = new ArrayList<>();

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

//        // 自定义点击事件  防止用户狂点  二逼测试的暴力测试
//        btn.setOnClickListener(new ForbidClickListener() {
//            @Override
//            public void forbidClick(View v) {
//                Map map = new HashMap<>();
//                map.put("BSID", "wFLZPV9qAS9Gwzx6RnfB3QzIMKb-kQ0sN0uc0OtTTuoszWlnO6FF6_Y7Q8GBpd9lyJx1lqFu6QVurCjTCemOZA");
//                myPresenter.postPreContent(APIs.MeiTuan, map, new MyInterfaces() {
//                    @Override
//                    public void chenggong(String json) {
//                        tv.setText("json===" + json);
//                    }
//
//                    @Override
//                    public void shibai(String ss) {
//                        MyUtils.setToast(ss);
//                    }
//                });
//            }
//        });

        btn.setOnClickListener(new ForbidClickListener() {
            @Override
            public void forbidClick(View v) {
                myPresenter.getPreContent(APIs.wxnew, new MyInterfaces() {
                    @Override
                    public void chenggong(String json) {
                        tv.setText("json===" + json);
                    }

                    @Override
                    public void shibai(String ss) {
                        MyUtils.setToast(ss);
                    }
                });
            }
        });

        // 上传多文件
        btup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 6.0权限适配
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DashApplication.WRITE_EXTERNAL_STORAGE);
                }else{
                    // 启动相册
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 1000);
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==DashApplication.WRITE_EXTERNAL_STORAGE){
            if(grantResults[0]!=-1){
                // 启动相册
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1000);
            }else{
                return;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 正面照的请求结果  相册
        if(requestCode==1000&resultCode==RESULT_OK){
            Uri uri = data.getData();
            File fileUri = ImageUtils.getFileUri(uri, this); // 将uri转成file
            // 将相册中获取到的照片重新选择路径存储 这里是用于适配机型的
            File photos1 = getPhotos(fileUri);
            LogUtils.i("jba","photos=="+ photos1.toString());
            tv.setText(photos1.toString());

            photos.clear();
            setPhotos(photos1,"identityFrontPic");
            setPhotos(photos1,"identityBackPic");
            setPhotos(photos1,"headerPic");
            setPhotos(photos1,"businessPic");
            Observable responseBodyCall = apiService.uploadFile(photos);
            responseBodyCall.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseServer() {
                        @Override
                        public void onSuccess(String json) {
                            tv.setText(json);
                        }

                        @Override
                        public void onErroy(String ss) {
                            tv.setText(ss);
                        }
                    });
        }
    }

    // 设置file类型
    private void setPhotos(File file,String key) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData(key, file.getName(), requestFile);
        photos.add(body);
    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn);
        btup = (Button) findViewById(R.id.btup);
        tv = (TextView) findViewById(R.id.tv);
    }
}

 

 

你可能感兴趣的:(Android上传Github)