Bläddra i källkod

修改图片上传

yanyi 5 år sedan
förälder
incheckning
ed56091fa7

+ 5 - 0
app/build.gradle

@@ -25,6 +25,11 @@ android {
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         }
     }
+
+    lintOptions {
+        abortOnError false
+    }
+
 }
 
 dependencies {

+ 473 - 0
app/src/main/java/com/mylove/okhttp/DateUtil.java

@@ -0,0 +1,473 @@
+package com.mylove.okhttp;
+
+import android.annotation.SuppressLint;
+
+import java.text.DateFormat;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+
+/**
+ * @author Administrator
+ * @date 2020/04/22 10:00
+ * @email ben@yanyi.red
+ * @overview
+ */
+public class DateUtil {
+    /**
+     * 时间戳转换成日期格式字符串
+     * seconds 精确到秒的字符串
+     */
+    public static String timeStamp2Date(String seconds, String format) {
+        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
+            return "";
+        }
+        if (format.isEmpty())
+            format = "yyyy-MM-dd HH:mm:ss";
+        SimpleDateFormat sdf = new SimpleDateFormat(format);
+        return sdf.format(new Date(Long.valueOf(seconds + "000")));
+    }
+
+    /**
+     * 计算两个日期型的时间相差多少时间
+     */
+    @SuppressLint("SimpleDateFormat")
+    public static String twoDateDistance(String endDates) {
+        endDates = timeStamp2Date(endDates, "yyyy-MM-dd HH:mm:ss");
+        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String date = dfs.format(new Date());
+        Date startDate = null;
+        try {
+            startDate = dfs.parse(date);
+            Date endDate = dfs.parse(endDates);
+            if (startDate == null || endDate == null) {
+                return null;
+            }
+            long timeLong = (endDate.getTime() - startDate.getTime()) / -1000;// 单位毫秒,除以1000转换成秒
+            // 单位秒
+            long month = 60 * 60 * 24 * 7 * 4;// 月
+            long week = 60 * 60 * 24 * 7;// 周
+            long day = 60 * 60 * 24;// 天
+            long hour = 60 * 60;// 小时
+            long minute = 60; // 分钟
+            long second = 1; // 秒
+
+            if (timeLong < minute) {
+                return timeLong / second + "秒前";
+            } else if (timeLong < hour) {
+                timeLong = timeLong / minute;
+                return timeLong + "分钟前";
+            } else if (timeLong < day) {
+                timeLong = timeLong / hour;
+                return timeLong + "小时前";
+            } else if (timeLong < week) {
+                timeLong = timeLong / day;
+                return timeLong + "天前";
+            } else if (timeLong < month) {
+                timeLong = timeLong / week;
+                return timeLong + "周前";
+            } else {
+                // 如果超过几周则显示日期
+                String str = new String(endDates);
+                String date1[] = str.split(" ");
+                return date1[0];
+            }
+        } catch (Exception e) {//
+            e.printStackTrace();
+        }
+        return dfs.format(startDate);
+
+    }
+
+    public static boolean timeCompare(String startTime, String endTime) {
+        try {
+            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+            Date startDate = df.parse(startTime);
+            Date endDate = df.parse(endTime);
+            long diff = endDate.getTime() - startDate.getTime();
+            long min = diff / (1000 * 60);
+            if (min < 1)
+                return false;
+            else
+                return true;
+        } catch (Exception e) {
+        }
+        return true;
+    }
+
+    /**
+     * 时间戳转换成日期格式字符串
+     *
+     * @param seconds 精确到秒的字符串
+     */
+    public static String timeStamp2Date(String seconds) {
+        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
+            return "";
+        }
+        String format = "yyyy-MM-dd";
+        SimpleDateFormat sdf = new SimpleDateFormat(format);
+        return sdf.format(new Date(Long.valueOf(seconds + "000")));
+    }
+
+    /**
+     * 日期格式字符串转换成时间戳
+     *
+     * @param format 如:yyyy-MM-dd HH:mm:ss
+     */
+    public static String date2TimeStamp(String date_str, String format) {
+        // 2016-03-13 03:29:00
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat(format);
+            return String.valueOf(sdf.parse(date_str).getTime() / 1000);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "";
+    }
+
+    /**
+     * 取得当前时间戳(精确到秒)
+     */
+    public static String timeStamp() {
+        long time = System.currentTimeMillis();
+        String t = String.valueOf(time / 1000);
+        return t;
+    }
+
+    /**
+     * 得到当前的时间
+     *
+     * @return 例如:2015-01-06 22:56
+     */
+    public static String getStringDate() {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String dateString = formatter.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * 得到当前的时间
+     */
+    public static String getStringDate(String format) {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat(format);
+        String dateString = formatter.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * 计算时间差
+     */
+    public static String TimeDifference(String startTime, String endTime, String format) {
+        String str = "";
+        try {
+            SimpleDateFormat sd = new SimpleDateFormat(format);
+            long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
+            long nh = 1000 * 60 * 60;// 一小时的毫秒数
+            long nm = 1000 * 60;// 一分钟的毫秒数
+            long ns = 1000;// 一秒钟的毫秒数long diff;try {
+            // 获得两个时间的毫秒时间差异
+            long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
+            long day = diff / nd;// 计算差多少天
+            long hour = diff % nd / nh;// 计算差多少小时
+            long min = diff % nd % nh / nm;// 计算差多少分钟
+            long sec = diff % nd % nh % nm / ns;// 计算差多少秒//输出结果
+            if (day > 0) {
+                str += day + "天";
+            }
+            if (hour > 0) {
+                str += hour + "小时";
+            }
+            if (min > 0) {
+                str += min + "分钟";
+            }
+            if (sec > 0) {
+                str += sec + "秒";
+            }
+        } catch (Exception e) {
+        }
+        return str;
+    }
+
+    /**
+     * 计算时间差
+     */
+    public static String TimeDifference(String startTime, String endTime) {
+        String str = "剩余";
+        try {
+            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
+            long nh = 1000 * 60 * 60;// 一小时的毫秒数
+            long nm = 1000 * 60;// 一分钟的毫秒数
+            long ns = 1000;// 一秒钟的毫秒数
+            // 获得两个时间的毫秒时间差异
+            Date start = new Date();
+            Date end = new Date();
+            start = sd.parse(timeStamp2Date(startTime, ""));
+            end = sd.parse(timeStamp2Date(endTime, ""));
+            long diff = end.getTime() - start.getTime();
+            long day = diff / nd;// 计算差多少天
+            long hour = diff % nd / nh;// 计算差多少小时
+            long min = diff % nd % nh / nm;// 计算差多少分钟
+            long sec = diff % nd % nh % nm / ns;// 计算差多少秒
+            if (day > 0) {
+                str += day + "天";
+            }
+            if (hour > 0) {
+                str += hour + "小时";
+            }
+            if (min > 0) {
+                str += min + "分钟";
+            }
+            if (sec > 0) {
+                str += sec + "秒";
+            }
+            if (diff < 0) {
+                str = "已过期";
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return str;
+    }
+
+    /**
+     * 结束日期是否大于开始日期
+     *
+     * @param startTime 开始时间 为时间戳类型
+     * @param endTime   结束时间 为时间戳类型
+     * @return true 表示为真
+     */
+    public static boolean TimeComparison(String startTime, String endTime) {
+        boolean mAfter = true;
+        try {
+            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+            long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
+            long nh = 1000 * 60 * 60;// 一小时的毫秒数
+            long nm = 1000 * 60;// 一分钟的毫秒数
+            long ns = 1000;// 一秒钟的毫秒数
+            // 获得两个时间的毫秒时间差异
+            Date start = new Date();
+            Date end = new Date();
+            start = sd.parse(timeStamp2Date(startTime, ""));
+            end = sd.parse(timeStamp2Date(endTime, ""));
+            long diff = end.getTime() - start.getTime();
+            long sec = diff % nd % nh % nm / ns;// 计算差多少秒
+            if (sec < 0) {
+                mAfter = false;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return mAfter;
+    }
+
+    public static String TimeDifferenceDay(String startTime, String endTime) {
+        String str = "";
+        try {
+            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd:mm:ss");
+            long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
+            long nh = 1000 * 60 * 60;// 一小时的毫秒数
+            // 获得两个时间的毫秒时间差异
+            long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
+            long day = diff / nd;// 计算差多少天
+            long hour = diff % nd / nh;// 计算差多少小时
+            if (day > 0) {
+                str += day + "天";
+            }
+            if (hour > 0) {
+                str += hour + "小时";
+            }
+            if (diff < 0) {
+                str = "已过期";
+            }
+        } catch (Exception e) {
+        }
+        return str;
+    }
+
+    /**
+     * 获取现在时间
+     *
+     * @return 返回短时间字符串格式yyyy-MM-dd
+     */
+    public static String getStringDateShort() {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+        String dateString = formatter.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * 获取时间 小时:分;秒 HH:mm:ss
+     */
+    public static String getTimeShort() {
+        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
+        Date currentTime = new Date();
+        String dateString = formatter.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
+     */
+    public static Date strToDateLong(String strDate) {
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        ParsePosition pos = new ParsePosition(0);
+        Date strtodate = formatter.parse(strDate, pos);
+        return strtodate;
+    }
+
+    /**
+     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
+     */
+    public static String dateToStrLong(Date dateDate) {
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String dateString = formatter.format(dateDate);
+        return dateString;
+    }
+
+    /**
+     * 将短时间格式时间转换为字符串 yyyy-MM-dd
+     */
+    public static String dateToStr(Date dateDate) {
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+        String dateString = formatter.format(dateDate);
+        return dateString;
+    }
+
+    /**
+     * 将短时间格式字符串转换为时间 yyyy-MM-dd
+     */
+    public static Date strToDate(String strDate) {
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+        ParsePosition pos = new ParsePosition(0);
+        Date strtodate = formatter.parse(strDate, pos);
+        return strtodate;
+    }
+
+    /**
+     * 得到现在时间
+     */
+    public static Date getNow() {
+        Date currentTime = new Date();
+        return currentTime;
+    }
+
+    /**
+     * 提取一个月中的最后一天
+     */
+    public static Date getLastDate(long day) {
+        Date date = new Date();
+        long date_3_hm = date.getTime() - 3600000 * 34 * day;
+        Date date_3_hm_date = new Date(date_3_hm);
+        return date_3_hm_date;
+    }
+
+    /**
+     * 得到现在时间
+     *
+     * @return 字符串 yyyyMMdd HHmmss
+     */
+    public static String getStringToday() {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
+        String dateString = formatter.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * 得到现在小时
+     */
+    public static String getHour() {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String dateString = formatter.format(currentTime);
+        String hour;
+        hour = dateString.substring(11, 13);
+        return hour;
+    }
+
+    /**
+     * 得到现在分钟
+     */
+    public static String getTime() {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        String dateString = formatter.format(currentTime);
+        String min;
+        min = dateString.substring(14, 16);
+        return min;
+    }
+
+    /**
+     * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。
+     */
+    public static String getUserDate(String sformat) {
+        Date currentTime = new Date();
+        SimpleDateFormat formatter = new SimpleDateFormat(sformat);
+        String dateString = formatter.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * @param strDate 当前时间
+     * @param pattern 时间格式
+     */
+    public static Date strToDate(String strDate, String pattern) {
+        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
+        ParsePosition pos = new ParsePosition(0);
+        Date strtodate = formatter.parse(strDate, pos);
+        return strtodate;
+    }
+
+    /**
+     * @param strDate 时间
+     * @param pattern 时间格式
+     */
+    public static String getDate(String strDate, String pattern) {
+        Date currentTime = strToDate(strDate, pattern);
+        SimpleDateFormat format1 = new SimpleDateFormat(pattern);
+        String dateString = format1.format(currentTime);
+        return dateString;
+    }
+
+    /**
+     * 判断星期几
+     */
+    public static String getWeek(String date) {
+        String week = "";
+        @SuppressLint("SimpleDateFormat")
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
+        Calendar c = Calendar.getInstance();
+        try {
+            c.setTime(format.parse(date));
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
+            week += "天";
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
+            week += "一";
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
+            week += "二";
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
+            week += "三";
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
+            week += "四";
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
+            week += "五";
+        }
+        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
+            week += "六";
+        }
+        return week;
+    }
+}

+ 22 - 23
app/src/main/java/com/mylove/okhttp/MainActivity.java

@@ -13,13 +13,10 @@ import com.benyanyi.permissionlib.PermissionCallBack;
 import com.benyanyi.permissionlib.PermissionHelper;
 import com.benyanyi.permissionlib.PermissionType;
 import com.benyanyi.permissionlib.msg.FailureMsg;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
 
 import java.util.HashMap;
 import java.util.Map;
 
-
 /**
  * @author myLove
  * @time 2017/11/16 19:18
@@ -49,17 +46,17 @@ public class MainActivity extends AppCompatActivity {
 //
 //            }
 //        });
-        String str = "<html></html>";
-        try {
-//            JSONObject jsonObject = new JSONObject(str);
-            JsonElement jsonParser = JsonParser.parseString(str);
-            Jlog.v(jsonParser.isJsonArray());
-            Jlog.v(jsonParser.isJsonObject());
-            Jlog.v(jsonParser.isJsonPrimitive());
-            Jlog.v(jsonParser.isJsonNull());
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
+//        String str = "<html></html>";
+//        try {
+////            JSONObject jsonObject = new JSONObject(str);
+//            JsonElement jsonParser = JsonParser.parseString(str);
+//            Jlog.v(jsonParser.isJsonArray());
+//            Jlog.v(jsonParser.isJsonObject());
+//            Jlog.v(jsonParser.isJsonPrimitive());
+//            Jlog.v(jsonParser.isJsonNull());
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
     }
 
     public void onClick(View view) {
@@ -83,15 +80,17 @@ public class MainActivity extends AppCompatActivity {
     }
 
     private void init() {
-        String url = "http://qxu1590330342.my3w.com/taihao/SimpleAlarm/update.json";
-        Map<Object, Object> oMap = new HashMap<>();
-        oMap.put("UserID", "110");
-        oMap.put("TypeID", "1");
-        oMap.put("Mac", "");
-        oMap.put("CodeID", "");
-        oMap.put("Status", "");
-        oMap.put("DataSet", "");
-        OkHttpUtil.getInstance(this).url(url, true).postText(oMap).async(new OnOkHttpListener<Object>() {
+        String url = "http://test.zhcjrwang.com/api/Test/Index";
+        Map<Object, Object> headerMap = new HashMap<>();
+        headerMap.put("app_key", "XiangKeLai");
+        String timeStamp = DateUtil.timeStamp();
+        headerMap.put("timestamp", timeStamp);
+        headerMap.put("sign", ("XiangKeLai1" + timeStamp).toUpperCase());
+        Jlog.v(headerMap);
+        Map<Object, Object> bodyMap = new HashMap<>();
+        bodyMap.put("data", "+fAFfMCGsMZqeS+gyrZm1A==");
+        Jlog.v(bodyMap);
+        OkHttpUtil.getInstance(this).url(url, true).postText(headerMap, bodyMap).async(new OnOkHttpListener<Object>() {
             @Override
             public void onCompleted() {
 

+ 1 - 1
okhttplib/bintrayUpload.gradle

@@ -7,7 +7,7 @@ def siteUrl = 'http://www.yanyis.space/yanyi/baseokhttp' // 项目主页。
 def gitUrl = 'http://www.yanyis.space/yanyi/baseokhttp.git' // Git仓库的url。
 
 group = "com.yanyi.benyanyi"// 唯一包名,比如compile 'com.ansen.http:okhttpencapsulation:1.0.1'中的com.ansen.http就是这里配置的。
-version = "2.0.2" //项目引用的版本号,比如compile 'com.ansen.http:okhttpencapsulation:1.0.1'中的1.0.1就是这里配置的。
+version = "2.0.3-base3" //项目引用的版本号,比如compile 'com.ansen.http:okhttpencapsulation:1.0.1'中的1.0.1就是这里配置的。
 install {
     repositories.mavenInstaller {
         // This generates POM.xml with proper parameters

+ 3 - 0
okhttplib/src/main/java/com/benyanyi/okhttp/type/Client.java

@@ -2,9 +2,11 @@ package com.benyanyi.okhttp.type;
 
 import android.content.Context;
 
+import java.util.Collections;
 import java.util.concurrent.TimeUnit;
 
 import okhttp3.OkHttpClient;
+import okhttp3.Protocol;
 
 /**
  * @author YanYi
@@ -26,6 +28,7 @@ class Client {
         return builder.connectTimeout(10, TimeUnit.SECONDS)
                 .writeTimeout(10, TimeUnit.SECONDS)
                 .readTimeout(10, TimeUnit.SECONDS)
+                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                 //支持HTTPS请求,跳过证书验证
                 .sslSocketFactory(SslConfig.createSSLSocketFactory(), SslConfig.getTrustManager())
                 .hostnameVerifier(HttpConfig.verifier())

+ 16 - 9
okhttplib/src/main/java/com/benyanyi/okhttp/type/HttpRequest.java

@@ -60,17 +60,22 @@ public class HttpRequest implements RequestType {
     }
 
     @Override
-    public RequestConfig postText(Map<Object, Object> map) {
+    public RequestConfig postText(Map<Object, Object> headerMap, Map<Object, Object> bodyMap) {
         FormBody.Builder builder = new FormBody.Builder();
-        if (FormatUtil.isMapNotEmpty(map)) {
-            mCacheName = mCacheName + map.toString();
-            for (Map.Entry<Object, Object> entry : map.entrySet()) {
+        if (FormatUtil.isMapNotEmpty(bodyMap)) {
+            mCacheName = mCacheName + bodyMap.toString();
+            for (Map.Entry<Object, Object> entry : bodyMap.entrySet()) {
                 builder.add(entry.getKey().toString(), entry.getValue().toString());
             }
         }
         FormBody build = builder.build();
-        request = new Request.Builder()
-                .url(url)
+        Request.Builder builder1 = new Request.Builder();
+        if (FormatUtil.isMapNotEmpty(headerMap)) {
+            for (Map.Entry<Object, Object> entry : headerMap.entrySet()) {
+                builder1.addHeader(entry.getKey().toString(), entry.getValue().toString());
+            }
+        }
+        request = builder1.url(url)
                 .post(build)
                 .build();
         return send();
@@ -139,9 +144,11 @@ public class HttpRequest implements RequestType {
         if (FormatUtil.isMapNotEmpty(map)) {
             for (Map.Entry<Object, Object> entry : map.entrySet()) {
                 File file = new File(entry.getValue().toString());
-                int indexOf = entry.getValue().toString().indexOf("/");
-                RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
-                String fileName = entry.getKey().toString().substring(indexOf + 1);
+//                int indexOf = entry.getValue().toString().indexOf("/");
+//                RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
+                RequestBody requestBody = RequestBody.create(file, MediaType.parse("multipart/form-data"));
+//                String fileName = entry.getKey().toString().substring(indexOf + 1);
+                String fileName = entry.getKey().toString();
                 builder.addFormDataPart(entry.getKey().toString(), fileName, requestBody);
             }
         }

+ 1 - 1
okhttplib/src/main/java/com/benyanyi/okhttp/type/RequestType.java

@@ -15,7 +15,7 @@ public interface RequestType {
 
     RequestConfig getText(Map<Object, Object> map);
 
-    RequestConfig postText(Map<Object, Object> map);
+    RequestConfig postText(Map<Object, Object> headerMap, Map<Object, Object> bodyMap);
 
     RequestConfig postJson(Map<Object, Object> map);
 

+ 1 - 1
okhttplib/src/main/java/com/benyanyi/okhttp/type/SslConfig.java

@@ -33,7 +33,7 @@ class SslConfig {
 
         SSLSocketFactory sslSocketFactory = null;
         try {
-            SSLContext sslContext = SSLContext.getInstance("SSL");
+            SSLContext sslContext = SSLContext.getInstance("TLS");
             sslContext.init(null, new TrustManager[]{getTrustManager()}, new SecureRandom());
             sslSocketFactory = sslContext.getSocketFactory();
         } catch (Exception e) {