SpringBoot項(xiàng)目中獲取IP地址的實(shí)現(xiàn)示例
前言
OkHttp 是一個(gè)由 Square 開發(fā)的高效、現(xiàn)代的 HTTP 客戶端庫(kù),用于 Android 和 Java 應(yīng)用程序。它支持 HTTP/2 和 SPDY 等現(xiàn)代網(wǎng)絡(luò)協(xié)議,并提供了多種功能和優(yōu)化,使其成為處理網(wǎng)絡(luò)請(qǐng)求的流行選擇。這次項(xiàng)目中我將會(huì)使用OkHttp來(lái)發(fā)送網(wǎng)絡(luò)請(qǐng)求
一、OkHttp是什么?
OkHttp 是一個(gè)由 Square 開發(fā)的高效、現(xiàn)代的 HTTP 客戶端庫(kù),用于 Android 和 Java 應(yīng)用程序。
二、使用步驟
1.OkHttp請(qǐng)求代碼
package com.easybbs.utils;
import com.easybbs.entity.enums.ResponseCodeEnum;
import com.easybbs.exception.BusinessException;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OKHttpUtils {
/**
* 請(qǐng)求超時(shí)時(shí)間5秒
*/
private static final int TIME_OUT_SECONDS = 5;
private static Logger logger = LoggerFactory.getLogger(OKHttpUtils.class);
private static OkHttpClient.Builder getClientBuilder() {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().followRedirects(false).addInterceptor(new RedirectInterceptor()).retryOnConnectionFailure(false);
clientBuilder.connectTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS).readTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS);
clientBuilder.sslSocketFactory(createSSLSocketFactory()).hostnameVerifier((hostname, session) -> true);
return clientBuilder;
}
private static Request.Builder getRequestBuilder(Map<String, String> header) {
Request.Builder requestBuilder = new Request.Builder();
if (null != header) {
for (Map.Entry<String, String> map : header.entrySet()) {
String key = map.getKey();
String value;
if (map.getValue() == null) {
value = "";
} else {
value = map.getValue();
}
requestBuilder.addHeader(key, value);
}
}
return requestBuilder;
}
private static FormBody.Builder getBuilder(Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
if (params == null) {
return builder;
}
for (Map.Entry<String, String> map : params.entrySet()) {
String key = map.getKey();
String value;
if (map.getValue() == null) {
value = "";
} else {
value = map.getValue();
}
builder.add(key, value);
}
return builder;
}
public static String getRequest(String url) throws BusinessException {
ResponseBody responseBody = null;
try {
OkHttpClient.Builder clientBuilder = getClientBuilder();
Request.Builder requestBuilder = getRequestBuilder(null);
OkHttpClient client = clientBuilder.build();
Request request = requestBuilder.url(url).build();
Response response = client.newCall(request).execute();
responseBody = response.body();
return responseBody.string();
} catch (SocketTimeoutException | ConnectException e) {
logger.error("OKhttp POST 請(qǐng)求超時(shí),url:{}", url, e);
throw new BusinessException(ResponseCodeEnum.CODE_900);
} catch (Exception e) {
logger.error("OKhttp GET 請(qǐng)求異常", e);
return null;
} finally {
if (responseBody != null) {
responseBody.close();
}
}
}
public static String postRequest(String url, Map<String, String> header, Map<String, String> params) throws BusinessException {
ResponseBody responseBody = null;
try {
OkHttpClient.Builder clientBuilder = getClientBuilder();
Request.Builder requestBuilder = getRequestBuilder(header);
FormBody.Builder builder = getBuilder(params);
OkHttpClient client = clientBuilder.build();
RequestBody requestBody = builder.build();
Request request = requestBuilder.url(url).post(requestBody).build();
Response response = client.newCall(request).execute();
responseBody = response.body();
String responseStr = responseBody.string();
return responseStr;
} catch (SocketTimeoutException | ConnectException e) {
logger.error("OKhttp POST 請(qǐng)求超時(shí),url:{}", url, e);
throw new BusinessException(ResponseCodeEnum.CODE_900);
} catch (Exception e) {
logger.error("OKhttp POST 請(qǐng)求異常,url:{}", url, e);
return null;
} finally {
if (responseBody != null) {
responseBody.close();
}
}
}
private static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return ssfFactory;
}
}
class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
class RedirectInterceptor implements Interceptor {
private static Logger logger = LoggerFactory.getLogger(RedirectInterceptor.class);
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
int code = response.code();
if (code == 307 || code == 301 || code == 302) {
//獲取重定向的地址
String location = response.headers().get("Location");
logger.info("重定向地址,location:{}", location);
//重新構(gòu)建請(qǐng)求
Request newRequest = request.newBuilder().url(location).build();
response = chain.proceed(newRequest);
}
return response;
}
}2.獲取Ip地址
代碼如下(示例):這個(gè)代碼只能獲取到省份地址,具體信息請(qǐng)看下面的詳細(xì)訪問(wèn)
public String getIpAddress(String ip){
try {
String url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip;
String responseJson = OKHttpUtils.getRequest(url);
if(null == responseJson){
return Constants.NO_ADDRESS;
}
Map<String,String> addressInfo = JsonUtils.convertJson2Obj(responseJson,Map.class);
return addressInfo.get("pro");
}catch (Exception e){
logger.error("獲取ip地址失敗",e);
}
return Constants.NO_ADDRESS;
}3.Controller層獲取Ip地址
@RequestMapping("/login")
public String login(HttpServletRequest request){
String ip = getIpAddr(request)
return getIpAddress(ip);
}
/**
* 獲取客戶端IP地址
* 由于客戶端的IP地址可能通過(guò)多個(gè)代理層轉(zhuǎn)發(fā),因此需要檢查多個(gè)HTTP頭字段以獲取真實(shí)IP。
* 此方法首先檢查“x-forwarded-for”頭,這是最常用的代理頭,然后嘗試其他不那么常見的頭字段。
* 如果所有嘗試都失敗,則回退到使用請(qǐng)求的遠(yuǎn)程地址。
*
* @param request HttpServletRequest對(duì)象,用于獲取客戶端IP地址。
* @return 客戶端的IP地址字符串。如果無(wú)法確定客戶端IP,則返回請(qǐng)求的遠(yuǎn)程地址。
*/
protected String getIpAddr(HttpServletRequest request) {
// 嘗試獲取“x-forwarded-for”頭,這是最常用的代理頭字段。
String ip = request.getHeader("x-forwarded-for");
// 檢查“x-forwarded-for”頭是否有效,并提取第一個(gè)IP地址。
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后會(huì)有多個(gè)ip值,第一個(gè)ip才是真實(shí)ip
if (ip.indexOf(",") != -1) {
ip = ip.split(",")[0];
}
}
// 如果“x-forwarded-for”頭無(wú)效,嘗試其他不那么常見的代理頭字段。
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
// 如果所有代理頭字段都無(wú)效,回退到使用請(qǐng)求的遠(yuǎn)程地址作為客戶端IP。
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 返回獲取到的IP地址,無(wú)論它是通過(guò)代理頭還是直接從請(qǐng)求中獲取。
return ip;
}
獲取信息如上,可以自行獲取其他信息
到此這篇關(guān)于SpringBoot項(xiàng)目中獲取IP地址的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot獲取IP地址內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot實(shí)現(xiàn)獲取客戶端IP地址的示例代碼
- SpringBoot項(xiàng)目中使用OkHttp獲取IP地址的示例代碼
- springboot如何獲取請(qǐng)求者的ip地址
- SpringBoot如何獲取客戶端的IP地址
- SpringBoot實(shí)現(xiàn)IP地址解析的示例代碼
- SpringBoot獲取客戶端的IP地址的實(shí)現(xiàn)示例
- SpringBoot整合Ip2region獲取IP地址和定位的詳細(xì)過(guò)程
- springboot獲取真實(shí)ip地址的方法實(shí)例
- springboot 獲取訪問(wèn)接口的請(qǐng)求的IP地址的實(shí)現(xiàn)
- springboot獲取訪問(wèn)的ip地址的實(shí)現(xiàn)步驟
相關(guān)文章
解決Spring?Security集成knife4j訪問(wèn)接口文檔出現(xiàn)403的問(wèn)題
這篇文章主要給大家介紹了如何解決Spring?Security集成knife4j訪問(wèn)接口文檔出現(xiàn)403的問(wèn)題,文中有詳細(xì)的解決方案,有需要的朋友可以參考閱讀下2023-07-07
SpringBoot 單元測(cè)試實(shí)戰(zhàn)(Mockito,MockBean)
這篇文章主要介紹了SpringBoot 單元測(cè)試實(shí)戰(zhàn)(Mockito,MockBean),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Maven分模塊開發(fā)與依賴管理和聚合和繼承及屬性深入詳細(xì)介紹
依賴管理是項(xiàng)目管理中非常重要的一環(huán)。幾乎任何項(xiàng)目開發(fā)的時(shí)候需要都需要使用到庫(kù)。而這些庫(kù)很可能又依賴別的庫(kù),這樣整個(gè)項(xiàng)目的依賴形成了一個(gè)樹狀結(jié)構(gòu),而隨著這個(gè)依賴的樹的延伸和擴(kuò)大,一系列問(wèn)題就會(huì)隨之產(chǎn)生2022-10-10
使用RestTemplate調(diào)用https接口跳過(guò)證書驗(yàn)證
這篇文章主要介紹了使用RestTemplate調(diào)用https接口跳過(guò)證書驗(yàn)證,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
Java實(shí)現(xiàn)Excel通用異步導(dǎo)出框架方式
我最近要做一個(gè)需求,就是設(shè)計(jì)一個(gè)通用的異步導(dǎo)出框架,如果數(shù)據(jù)量小于5W那么直接進(jìn)行導(dǎo)出,數(shù)據(jù)大于5W則創(chuàng)建異步導(dǎo)出任務(wù),并且前端可以刷新該任務(wù)進(jìn)行,然后后面所有相關(guān)功能的導(dǎo)出都使用此框架進(jìn)行操作,思來(lái)想去實(shí)現(xiàn)后,想著該需求應(yīng)該符合大部分實(shí)際工作的場(chǎng)景,特此分享!2025-10-10

