日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

HttpUtil發送外部請求包工具類

作者:枯楓葉 更新時間: 2022-08-05 編程語言
package com.sport.sportcloudmarathonh5.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;

/**
 * @author zdj
 * @version 1.0
 * @date 2022-07-20 11:40:05
 */
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    /**
     * 發送post請求
     * @param requestUrl 請求地址
     * @param requestParam 請求參數
     */
    public static JSONObject sendPost(String requestUrl, JSONObject requestParam){
        JSONObject result = new JSONObject();
        // 1. 創建HttpClient對象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 創建HttpPost對象
        HttpPost post = new HttpPost(requestUrl);
        post.setEntity(new StringEntity(requestParam.toString(), HTTP.UTF_8));  // 這里這只字符格式,可以防止中文亂碼
        // 3. 執行請求并處理響應
        try {
            CloseableHttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = JSONObject.parseObject(EntityUtils.toString(entity));
            }
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4. 釋放資源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 發送get請求
     * @param requestUrl 請求地址
     * @param requestParam 請求參數(有參數的情況下格式為:name='張三'&sex=13&adress='杭州市余杭區')
     */
    public static JSONObject sendGet(String requestUrl, String requestParam){
        JSONObject result = new JSONObject();
        // 1. 創建HttpClient對象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 創建HttpGet對象
        HttpGet httpGet = new HttpGet(ObjectUtils.isEmpty(requestParam) ? requestUrl : (requestUrl +"?"+ requestParam));
        // 3. 執行GET請求
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 4. 獲取響應實體
            HttpEntity entity = response.getEntity();
            // 5. 處理響應實體
            if (entity != null) {
                result = JSONObject.parseObject(EntityUtils.toString(entity));
            }
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 6. 釋放資源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 獲取IP地址
     * 使用Nginx等反向代理軟件, 則不能通過request.getRemoteAddr()獲取IP地址
     * 如果使用了多級反向代理的話,X-Forwarded-For的值并不止一個,而是一串IP地址,X-Forwarded-For中第一個非unknown的有效IP字符串,則為真實IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("獲取ip地址異常:" + e);
        }
        //使用代理,則獲取第一個IP地址
        if(StringUtils.isEmpty(ip) ) {
            if(ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 根據ip獲取歸屬地
     * @param ip
     * @return
     */
    public static String getAddress(String ip) {
        URL url = HttpUtil.class.getClassLoader().getResource("ip2region.db");
        File file;
        if (url != null) {
            file = new File(url.getFile());
        } else {
            return null;
        }
        if (!file.exists()) {
            logger.error("Error: Invalid ip2region.db file, filePath:" + file.getPath());
            return null;
        }
        //查詢算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        //DbSearcher.BINARY_ALGORITHM //Binary
        //DbSearcher.MEMORY_ALGORITYM //Memory
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, file.getPath());
            Method method;
            switch (algorithm){
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
                default:
                    return null;
            }
            DataBlock dataBlock;
            if (!Util.isIpAddress(ip)) {
                logger.error("Error: Invalid ip address");
                return null;
            }
            dataBlock  = (DataBlock) method.invoke(searcher, ip);
            return dataBlock.getRegion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判斷當前ip的城市是否在指定的城市中
     * @param curCity 當前ip城市數據
     * @param targetCity 目標城市
     * @return
     */
    public static boolean judgeCurCityInTargetCity(String curCity, String targetCity) {
        return curCity.contains(targetCity) ? true : false;
    }

    /**
     * 驗證指定的ip地址是否在指定的城市
     * @param args
     */
    public static void main(String[] args) {
        if(judgeCurCityInTargetCity(getAddress("183.157.41.135"), "湖州")){
            System.out.println("在");
        } else {
            System.out.println("不在");
        }
    }
}

測試:

/**
     * 立即抽取
     * @param token 用戶信息
     * @return
     */
    @RedisLimitStream(reqName = "立即抽取", reqLimit = 1000)
    @ApiOperation(value = "立即抽取", notes = "立即抽取", httpMethod = "GET")
    @RequestMapping(value = "/atOnceExtract", method = RequestMethod.GET)
    public ResultVO<AtOnceExtractVO> atOnceExtract(HttpServletRequest request) {
        try {
            // 不在湖州,不能報名
            if(!HttpUtil.judgeCurCityInTargetCity(HttpUtil.getAddress(HttpUtil.getIpAddr(request)), "湖州")){
                return ResultVO.error("你不在湖州市內");
            }
          
            // 調用服務處理業務
            return couponRobticketUserRecordService.atOnceExtract(userInfoVO);
        } catch (Exception e) {
            logger.error("立即抽取出現異常:", e);
        }

        // 返回結果
        return ResultVO.exp();
    }

原文鏈接:https://blog.csdn.net/gelinwangzi_juge/article/details/125930548

欄目分類
最近更新