HttpUtil发送外部请求包工具类

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("不在");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/gelinwangzi_juge/article/details/125930548