前言
okhttp 是一个由 square 开发的高效、现代的 http 客户端库,用于 android 和 java 应用程序。它支持 http/2 和 spdy 等现代网络协议,并提供了多种功能和优化,使其成为处理网络请求的流行选择。这次项目中我将会使用okhttp来发送网络请求
一、okhttp是什么?
okhttp 是一个由 square 开发的高效、现代的 http 客户端库,用于 android 和 java 应用程序。
二、使用步骤
1.okhttp请求代码
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 { /** * 请求超时时间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 请求超时,url:{}", url, e); throw new businessexception(responsecodeenum.code_900); } catch (exception e) { logger.error("okhttp get 请求异常", 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 请求超时,url:{}", url, e); throw new businessexception(responsecodeenum.code_900); } catch (exception e) { logger.error("okhttp post 请求异常,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); //重新构建请求 request newrequest = request.newbuilder().url(location).build(); response = chain.proceed(newrequest); } return response; } }
2.获取ip地址
代码如下(示例):这个代码只能获取到省份地址,具体信息请看下面的详细访问
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地址可能通过多个代理层转发,因此需要检查多个http头字段以获取真实ip。 * 此方法首先检查“x-forwarded-for”头,这是最常用的代理头,然后尝试其他不那么常见的头字段。 * 如果所有尝试都失败,则回退到使用请求的远程地址。 * * @param request httpservletrequest对象,用于获取客户端ip地址。 * @return 客户端的ip地址字符串。如果无法确定客户端ip,则返回请求的远程地址。 */ protected string getipaddr(httpservletrequest request) { // 尝试获取“x-forwarded-for”头,这是最常用的代理头字段。 string ip = request.getheader("x-forwarded-for"); // 检查“x-forwarded-for”头是否有效,并提取第一个ip地址。 if (ip != null && ip.length() != 0 && !"unknown".equalsignorecase(ip)) { // 多次反向代理后会有多个ip值,第一个ip才是真实ip if (ip.indexof(",") != -1) { ip = ip.split(",")[0]; } } // 如果“x-forwarded-for”头无效,尝试其他不那么常见的代理头字段。 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"); } // 如果所有代理头字段都无效,回退到使用请求的远程地址作为客户端ip。 if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) { ip = request.getremoteaddr(); } // 返回获取到的ip地址,无论它是通过代理头还是直接从请求中获取。 return ip; }
获取信息如上,可以自行获取其他信息
总结
本次项目总结如何获取ip地址
到此这篇关于springboot项目中使用okhttp获取ip地址的示例代码的文章就介绍到这了,更多相关springboot okhttp获取ip地址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论