網站首頁 編程語言 正文
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
相關推薦
- 2022-07-07 go語言中如何使用select的實現示例_Golang
- 2022-11-03 C++編譯期循環獲取變量類型詳情_C 語言
- 2022-08-15 數據結構之有頭鏈表的實現
- 2022-07-13 4:thingsboard的實體與關系
- 2022-04-19 Django的開發步驟原來是這樣的_python
- 2022-01-11 Css設置border從中間向兩邊的顏色漸進效果
- 2024-03-15 Redis中RDB和AOF
- 2022-11-03 C++構造函數初始化列表的實現詳解_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支