一些帮助类:CommonUtils,,,,OkHttp3Util_yaozhipu的博客-程序员信息网

CommonUtils

public class CommonUtils {
    public static final String TAG = "Dash";//sp文件的xml名称
    private static SharedPreferences sharedPreferences;

    /**
     * DashApplication.getAppContext()可以使用,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用
     * @param layoutId
     * @return
     */
    public static View inflate(int layoutId) {
        View view = View.inflate(DashApplication.getAppContext(), layoutId, null);
        return view;
    }

    /**
     * dip---px
     *
     * @param dip 设备独立像素device independent px....1dp = 3px 1dp = 2px 1dp = 1.5px
     * @return
     */
    public static int dip2px(int dip) {
        //获取像素密度
        float density = DashApplication.getAppContext().getResources().getDisplayMetrics().density;
        //
        int px = (int) (dip * density + 0.5f);//100.6
        return px;

    }

    /**
     * px-dip
     *
     * @param px
     * @return
     */
    public static int px2dip(int px) {
        //获取像素密度
        float density = DashApplication.getAppContext().getResources().getDisplayMetrics().density;
        //
        int dip = (int) (px / density + 0.5f);
        return dip;

    }

    /**
     * 获取资源中的字符串
     * @param stringId
     * @return
     */
    public static String getString(int stringId) {
        return DashApplication.getAppContext().getResources().getString(stringId);
    }

    public static Drawable getDrawable(int did) {
        return DashApplication.getAppContext().getResources().getDrawable(did);
    }

    public static int getDimens(int id) {
        return DashApplication.getAppContext().getResources().getDimensionPixelSize(id);
    }

    /**
     * sp存入字符串类型的值
     * @param flag
     * @param str
     */
    public static void saveSp(String flag, String str) {
        if (sharedPreferences == null) {
            sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(flag, str);
        edit.commit();
    }

    public static String getSp(String flag) {
        if (sharedPreferences == null) {
            sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
        }
        return sharedPreferences.getString(flag, "");
    }

    public static boolean getBoolean(String tag) {
        if (sharedPreferences == null) {
            sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
        }
        return sharedPreferences.getBoolean(tag, false);
    }

    public static void putBoolean(String tag, boolean content) {
        if (sharedPreferences == null) {
            sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(tag, content);
        edit.commit();
    }

    /**
     * 清除sp数据
     * @param tag
     */
    public static void clearSp(String tag) {
        if (sharedPreferences == null) {
            sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.remove(tag);
        edit.commit();
    }

    /**
     * 自己写的运行在主线程的方法
     * 如果是主线程,执行任务,否则使用handler发送到主线程中去执行
     *
     *
     * @param runable
     */
    public static void runOnUIThread(Runnable runable) {
        //先判断当前属于子线程还是主线程
        if (android.os.Process.myTid() == DashApplication.getMainThreadId()) {
            runable.run();
        } else {
            //子线程
            DashApplication.getAppHanler().post(runable);
        }
    }
}
++++++++++++++++++++++++++++++++++++++++++++++++

OkHttp3Util

public class OkHttp3Util {

    /**
     * 懒汉 安全 加同步
     * 私有的静态成员变量 只声明不创建
     * 私有的构造方法
     * 提供返回实例的静态方法
     */
    private static OkHttpClient okHttpClient = null;


    private OkHttp3Util() {
    }

    public static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            //加同步安全
            synchronized (OkHttp3Util.class) {
                if (okHttpClient == null) {
                    //okhttp可以缓存数据....指定缓存路径
                    File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
                    //指定缓存大小
                    int cacheSize = 10 * 1024 * 1024;

                    okHttpClient = new OkHttpClient.Builder()//构建器
                            .connectTimeout(15, TimeUnit.SECONDS)//连接超时
                            .writeTimeout(20, TimeUnit.SECONDS)//写入超时
                            .readTimeout(20, TimeUnit.SECONDS)//读取超时

                            //.addInterceptor(new CommonParamsInterceptor())//添加的是应用拦截器...公共参数
                            //.addNetworkInterceptor(new CacheInterceptor())//添加的网络拦截器

                            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))//设置缓存
                            .build();
                }
            }

        }

        return okHttpClient;
    }

    /**
     * get请求
     * 参数1 url
     * 参数2 回调Callback
     */

    public static void doGet(String oldUrl, Callback callback) {

        //要添加的公共参数...map
        Map<String,String> map = new HashMap<>();
        map.put("source","android");

        StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder

        stringBuilder.append(oldUrl);

        if (oldUrl.contains("?")){
            //?在最后面....2类型
            if (oldUrl.indexOf("?") == oldUrl.length()-1){

            }else {
                //3类型...拼接上&
                stringBuilder.append("&");
            }
        }else {
            //不包含? 属于1类型,,,先拼接上?号
            stringBuilder.append("?");
        }

        //添加公共参数....
        for (Map.Entry<String,String> entry: map.entrySet()) {
            //拼接
            stringBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        //删掉最后一个&符号
        if (stringBuilder.indexOf("&") != -1){
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
        }

        String newUrl = stringBuilder.toString();//新的路径


        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //创建Request
        Request request = new Request.Builder().url(newUrl).build();
        //得到Call对象
        Call call = okHttpClient.newCall(request);
        //执行异步请求
        call.enqueue(callback);


    }

    /**
     * post请求
     * 参数1 url
     * 参数2 Map<String, String> params post请求的时候给服务器传的数据
     *      add..("","")
     *      add()
     */

    public static void doPost(String url, Map<String, String> params, Callback callback) {
        //要添加的公共参数...map
        Map<String,String> map = new HashMap<>();
        map.put("source","android");


        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //3.x版本post请求换成FormBody 封装键值对参数

        FormBody.Builder builder = new FormBody.Builder();
        //遍历集合
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));

        }

        //添加公共参数
        for (Map.Entry<String,String> entry: map.entrySet()) {
            builder.add(entry.getKey(),entry.getValue());
        }

        //创建Request
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);

    }

    /**
     * post请求上传文件....包括图片....流的形式传任意文件...
     * 参数1 url
     * file表示上传的文件
     * fileName....文件的名字,,例如aaa.jpg
     * params ....传递除了file文件 其他的参数放到map集合
     *
     */
    public static void uploadFile(String url, File file, String fileName,Map<String,String> params) {
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        //参数
        if (params != null){
            for (String key : params.keySet()){
                builder.addFormDataPart(key,params.get(key));
            }
        }
        //文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,此处应该改变
        builder.addFormDataPart("file",fileName,RequestBody.create(MediaType.parse("application/octet-stream"),file));

        //构建
        MultipartBody multipartBody = builder.build();

        //创建Request
        Request request = new Request.Builder().url(url).post(multipartBody).build();

        //得到Call
        Call call = okHttpClient.newCall(request);
        //执行请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("upload",e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //上传成功回调 目前不需要处理
                if (response.isSuccessful()){
                    String s = response.body().string();
                    Log.e("upload","上传--"+s);
                }
            }
        });

    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一:请求Url
     * 参数二:请求的JSON
     * 参数三:请求回调
     */
    public static void doPostJson(String url, String jsonParams, Callback callback) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);

    }

    /**
     * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
     * 参数er:请求Url
     * 参数san:保存文件的文件夹....download
     */
    public static void download(final Activity context, final String url, final String saveDir) {
        Request request = new Request.Builder().url(url).build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //com.orhanobut.logger.Logger.e(e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();//以字节流的形式拿回响应实体内容
                    //apk保存路径
                    final String fileDir = isExistDir(saveDir);
                    //文件
                    File file = new File(fileDir, getNameFromUrl(url));

                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }

                    fos.flush();

                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show();
                        }
                    });

                    //apk下载完成后 调用系统的安装方法
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    context.startActivity(intent);


                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();


                }
            }
        });

    }

    /**
     * 判断下载目录是否存在......并返回绝对路径
     *
     * @param saveDir
     * @return
     * @throws IOException
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            Log.e("savePath", savePath);
            return savePath;
        }
        return null;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 公共参数拦截器
     */
    private static class CommonParamsInterceptor implements Interceptor{

        //拦截的方法
        @Override
        public Response intercept(Chain chain) throws IOException {

            //获取到请求
            Request request = chain.request();
            //获取请求的方式
            String method = request.method();
            //获取请求的路径
            String oldUrl = request.url().toString();

            Log.e("---拦截器",request.url()+"---"+request.method()+"--"+request.header("User-agent"));

            //要添加的公共参数...map
            Map<String,String> map = new HashMap<>();
            map.put("source","android");

            if ("GET".equals(method)){
                // 1.http://www.baoidu.com/login                --------? key=value&key=value
                // 2.http://www.baoidu.com/login?               --------- key=value&key=value
                // 3.http://www.baoidu.com/login?mobile=11111    -----&key=value&key=value

                StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder

                stringBuilder.append(oldUrl);

                if (oldUrl.contains("?")){
                    //?在最后面....2类型
                    if (oldUrl.indexOf("?") == oldUrl.length()-1){

                    }else {
                        //3类型...拼接上&
                        stringBuilder.append("&");
                    }
                }else {
                    //不包含? 属于1类型,,,先拼接上?号
                    stringBuilder.append("?");
                }

               //添加公共参数....
                for (Map.Entry<String,String> entry: map.entrySet()) {
                    //拼接
                    stringBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }

                //删掉最后一个&符号
                if (stringBuilder.indexOf("&") != -1){
                    stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
                }

                String newUrl = stringBuilder.toString();//新的路径

                //拿着新的路径重新构建请求
                request = request.newBuilder()
                        .url(newUrl)
                        .build();


            }else if ("POST".equals(method)){
                //先获取到老的请求的实体内容
                RequestBody oldRequestBody = request.body();//....之前的请求参数,,,需要放到新的请求实体内容中去

                //如果请求调用的是上面doPost方法
                if (oldRequestBody instanceof FormBody){
                    FormBody oldBody = (FormBody) oldRequestBody;

                    //构建一个新的请求实体内容
                    FormBody.Builder builder = new FormBody.Builder();
                    //1.添加老的参数
                    for (int i=0;i<oldBody.size();i++){
                        builder.add(oldBody.name(i),oldBody.value(i));
                    }
                    //2.添加公共参数
                    for (Map.Entry<String,String> entry:map.entrySet()) {

                        builder.add(entry.getKey(),entry.getValue());
                    }

                    FormBody newBody = builder.build();//新的请求实体内容

                    //构建一个新的请求
                    request = request.newBuilder()
                            .url(oldUrl)
                            .post(newBody)
                            .build();
                }


            }


            Response response = chain.proceed(request);

            return response;
        }
    }

    /**
     * 网络缓存的拦截器......注意在这里更改cache-control头是很危险的,一般客户端不进行更改,,,,服务器端直接指定
     *
     * 没网络取缓存的时候,一般都是在数据库或者sharedPerfernce中取出来的
     *
     *
     *
     */
    /*private static class CacheInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            //老的响应
            Response oldResponse = chain.proceed(chain.request());

            *//*if (NetUtils.isNetworkConnected(DashApplication.getAppContext())){
                int maxAge = 120; // 在线缓存在2分钟内可读取

                return oldResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            }else {
                int maxStale = 60 * 60 * 24 * 14; // 离线时缓存保存2周
                return oldResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }*//*

        }
    }*/
}


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yaozhipu/article/details/78850416

智能推荐

用 kubeadm --config 创建 k8s 集群_金庆的博客-程序员信息网_kubeadm.conf

用 kubeadm –config 创建 k8s 集群(金庆的专栏 2018.5)利用阿里云的yum镜像和docker镜像,可以不用代理直接安装创建 k8s 集群。K8s 版本为 v1.10.3参考:https://blog.csdn.net/u010209217/article/details/78533936 Kubernetes 1.7.5部署以及kubernates-...

tensorflow学习之二 alexnet vgg resnet目标分类_xiao__run的博客-程序员信息网

1、引言这节我们将介绍图像分类问题,任务是给定一个输入图片,将其指派到一个已知的混合类别中的某一个标签。图像分类是计算机视觉领域的核心问题之一,尽管它很(看上去)很简单,但是却有广泛的实践应用。而且,在之后的我将会使用tensorlfow 实现图像分割,许多其他的看上去不同的计算机视觉任务(例如物体识别,分割),都能够还原成图像分类。例如,在下图中,一个图像分类模型将一个图片分配给四个类别(c...

用iPhone/iPad VNC连接树莓派连不上的解决办法_CrossEntropy的博客-程序员信息网

需要在iPhone/iPad系统设置中,允许VNC Viewer 使用无线与蜂窝移动数据。

linux下搭建阿帕奇服务器_iaMay_____的博客-程序员信息网_linux阿帕奇服务器

安装httpd 基本配置 通过ip来禁止用户登陆 如下添加 黑名单ip  Deny与Allow的先后顺序决定先读谁,以此来决定时黑名单还是白名单如图成功设置通过用户方式访问  htpasswd -cm apacheuser linux   第一次建立用户需要-c,以后的不需要,否则会覆盖之前的用户修改如下 如图成功搭建虚拟主机注释掉Require user       添加Require vali...

linux学习笔记(兄弟连)day9.14_JAVA秃的博客-程序员信息网

Linux系统简介目录Linux系统简介一.UNIX与Linux发展史1.1UNIX发展史1.2UNIX主要发行版本1.3Linux发展史1.4linux发行版本二.开源软件简介2.1 开源软件的特点2.2支撑互联网的开源技术三.Linux应用领域3.1基于Linux的企业服务器3.2嵌入式应用3.3Linux在电影娱乐业四.Linux学习方法4.1为什么用命令行4.2解决问题的智慧一.UNIX与Linux发展史1.1UNIX发..

bzoj4552 [HEOI2016/TJOI2016]排序(二分+线段树)_overcastt的博客-程序员信息网

题解哇二分..真厉害! 每次二分一个数,然后把小于x的数当做0,大于的当做1 然后对于每一段,想把它排好序,也就是把1和0排好序,也就是把部分改成1、部分改成0。而这一段里面有几个1就可以区间和解决了。 即如果已经求出这段有cnt个1,升序操作[l,r-cnt]=0,[r-cnt+1,r]=1;降序操作[l,l+cnt-1]=1,[l-cnt,r]=0代码#include &amp;...

随便推点

@ApiModel and @ApiModelProperty 用法_Lanje Wang的博客-程序员信息网_apimodelproperty依赖

import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import java.io.Serializable;@ApiModelpublic class XXXX implements Serializable { private static final long serialVersionUID = XXXXL; @ApiModelProperty( ...

如何用maven 手动把本地jar安装到本地仓库和将本地项目打包并安装到本地资源仓库_vampire2777的博客-程序员信息网

1.命令打包mvn install:install-file -DgroupId=com.unionpay -DartifactId=mcm -Dversion=1.0 -Dfile=D:\360安全浏览器下载\中国银联小微商户资金服务接口的对外接口需求\McmServiceResWsClient-0.9.0.jar -Dpackaging=jar2.maven使用<dependency>

Java - java虚拟机概述、jre, jdk, jvm的区别_guaw007的博客-程序员信息网

Java虚拟机概述 Java推出时,提出了 &quot;Write Once,Run Anywhere&quot; 的口号,能达到跨平台运行代码这件事,就必须归功于java虚拟机 (Java Virtual Machine)的功劳了 传统C/C++是直接把程序员写的.c/.cpp代码,编译成那个平台(ex: Windows)能看懂的machine code,所以当编译一次之后,生成出来的这...

对JsonArray根据JsonObject中的某一字段排序_程序员阿文的博客-程序员信息网_jsonarray根据字段排序

方式一:Collections.sort(list, new Comparator() {})List&lt;JSONObject&gt; list = JSONArray.parseArray(resultArrays.toJSONString(), JSONObject.class);Collections.sort(list, new Comparator&lt;JSONObject&gt;() { //排序字段 private final String FIELD_NAME =

DirectX10安装路径自动生成DXSDK_DIR_weixin_30709929的博客-程序员信息网

DXSDK_DIRC:\Program Files (x86)\Microsoft DirectX SDK (February 2010)\转载于:https://www.cnblogs.com/wainiwann/p/9482970.html

ubuntu18.04无软件源导致安装失败_晓文……的博客-程序员信息网

仓库 “http://ppa.launchpad.net/xxx/xx/ubuntubionic Release” 没有 Release 文件 修改/etc/apt/sources.list.d/xxx-bionic.list文件,将bionic(18.04版本代号)改成xenial(16.04版本代号) sudo apt-get update &amp;&amp; apt-ge...