HTTP4.5.9工具類/時間工具類

HTTP4.5.9工具類

package com.xinyunfu.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author XRZ
 * @date 2019/8/15
 * @Description :
 */
public class HttpClientUtils {

    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通過址默認配置創建一個httpClient實例
            httpClient = HttpClients.createDefault();
            // 創建httpGet遠程連接實例
            HttpGet httpGet = new HttpGet(url);
            // 設置請求頭信息,鑑權
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 設置配置請求參數
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連接主機服務超時時間
                    .setConnectionRequestTimeout(35000)// 請求超時時間
                    .setSocketTimeout(60000)// 數據讀取超時時間
                    .build();
            // 爲httpGet實例設置配置
            httpGet.setConfig(requestConfig);
            // 執行get請求得到返回對象
            response = httpClient.execute(httpGet);
            // 通過返回對象獲取返回數據
            HttpEntity entity = response.getEntity();
            // 通過EntityUtils中的toString方法將結果轉換爲字符串
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 創建httpClient實例
        httpClient = HttpClients.createDefault();
        // 創建httpPost遠程連接實例
        HttpPost httpPost = new HttpPost(url);
        // 配置請求參數實例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設置連接主機服務超時時間
                .setConnectionRequestTimeout(35000)// 設置連接請求超時時間
                .setSocketTimeout(60000)// 設置讀取數據連接超時時間
                .build();
        // 爲httpPost實例設置配置
        httpPost.setConfig(requestConfig);
        // 設置請求頭
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封裝post請求參數
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通過map集成entrySet方法獲取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循環遍歷,獲取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 爲httpPost設置封裝好的請求參數
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient對象執行post請求,並返回響應參數對象
            httpResponse = httpClient.execute(httpPost);
            // 從響應對象中獲取響應內容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

時間工具類

package com.xinyunfu.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @author XRZ
 * @date 2019/7/8 0008
 * @Description : 時間工具類
 */
@Component
public class TimeUtils {

    /**
     * 未付款訂單的限時 (12小時)
     */
    public static long ORDER_UNPAID;

    /**
     * 已取消訂單自動刪除的限時 (7天)
     */
    public static long ORDER_AUTO_DELETE;

    /**
     * 自動確認收貨的限時 (7天)
     */
    public static long ORDER_AUTO_COMFIRM_GOODS;

    /**
     * 延遲釋放券的時長 (15分鐘)
     */
    public static long ORDER_RELEASE_COUPON;


    @Value("${order.unpaid}")
    public void setOrderUnpaid(long orderUnpaid) {
        ORDER_UNPAID = orderUnpaid;
    }
    @Value("${order.auto.delete}")
    public void setOrderAutoDelete(long orderAutoDelete) {
        ORDER_AUTO_DELETE = orderAutoDelete;
    }
    @Value("${order.auto.comfirmGoods}")
    public void setOrderAutoComfirmGoods(long orderAutoComfirmGoods) { ORDER_AUTO_COMFIRM_GOODS = orderAutoComfirmGoods; }
//    @Value("${order.releaseCoupon}")
//    public void setOrderReleaseCoupon(long orderReleaseCoupon) {
//        ORDER_RELEASE_COUPON = orderReleaseCoupon;
//    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 獲取1年後的日期
     * @return
     */
    public static String getNextTime(){
        return LocalDateTime.now().minusYears(-1).format(formatter);
    }
    /**
     * 獲取指定 毫秒數 後的時間
     * @return  yyyy-MM-dd HH:mm:ss
     */
    public static String payTimeOut(long s){
        return LocalDateTime.now().minusSeconds(-(s/1000)).format(formatter2);
    }


    /**
     * 獲取當前時間
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getDate(){
        return sdf.format(new Date());
    }

    /**
     * 獲取指定日期時間
     * @param timestamp
     * @return yyyy-MM-dd
     */
    public static String getStr(Timestamp timestamp){
        return sdf2.format(new Date(timestamp.getTime()));
    }

    /**
     * 獲取指定日期時間
     * @param timestamp
     * @return yyyy-MM-dd HH:mm:sss
     */
    public static String getStr2(Timestamp timestamp){
        return sdf.format(new Date(timestamp.getTime()));
    }

    /**
     * 獲取剩餘時間
     *
     *          未來時間 = 下單時間 + 限時時間
     *          剩餘時間 = 未來時間 - 當前時間
     *
     * @param timeLimit 限時時間
     * @param startTime 下單時間/發貨時間
     * @return 剩餘時間 (XX天XX分XX秒)
     */
    public static String getStrTime(long timeLimit,long startTime){
        //  未來時間 = 當前時間 + 限時時間
        long time = startTime + timeLimit;
        return getStrDateTime(time,System.currentTimeMillis());
    }

    /**
     * 0天0小時15分鐘30秒
     * @param after  未來時間
     * @param before 過去時間
     * @return 0天0小時15分鐘30秒
     */
    private  static String getStrDateTime(long after,long before) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long ns = 1000;
        long diff = after - before;
        // 計算差多少天
        long day = diff / nd;
        // 計算差多少小時
        long hour = diff % nd / nh;
        // 計算差多少分鐘
        long min = diff % nd % nh / nm;
        // 計算差多少秒//輸出結果
         long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小時" + min + "分鐘" + sec + "秒";
    }



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章