通过淘宝接口免费获取IP地址信息

1.获取互联网访问IP信息

    一般获取互联网访问的IP的相关信息一般都是收费接口,免费的接口不多,我使用到一个接口如下:

  

http://ip.taobao.com/service/getIpInfo.php?ip=139.189.109.174

这个是淘宝的接口,直接可以查询对应的IP信息,免费使用哦。在Java程序里可以直接封装调用。

 

对封装获取IP的地址的方法代码如下:

HttpRequestUtils.java

package com.seezoon.framework.common.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSON;
import com.seezoon.framework.common.context.exception.ServiceException;

/**
 * 对性能和参数要求敏感,需要自行利用 HttpPoolClient 对象自行构造
 * 
 * @author hdf 2018年4月23日
 */
public class HttpRequestUtils {

    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);

    private static String DEFAULT_CHARSET = "UTF-8";

    private static HttpPoolClient defaultHttpPoolClient = new HttpPoolClient();

    public static <T> T doGet(String url, Map<String, String> params, Class<T> clazz) {
        return JSON.parseObject(doGet(url, params), clazz);
    }

    public static <T> T doPost(String url, Map<String, String> params, Class<T> clazz) {
        return JSON.parseObject(doPost(url, params), clazz);
    }

    public static <T> T postJson(String url, Map<String, String> params, Class<T> clazz) {
        return JSON.parseObject(postJson(url, params), clazz);
    }

    public static String postJson(String url, Map<String, String> params) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.APPLICATION_JSON));
        return execute(httpPost);
    }

    public static String postXml(String url,String content) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(content, ContentType.create("application/xml", "UTF-8")));
        return execute(httpPost);
    }
    public static String doGet(String url, Map<String, String> params) {
        Assert.hasLength(url, "请求地址为空");
        try {
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(getNameValuePair(params));
            HttpGet httpGet = new HttpGet(builder.toString());
            String result = execute(httpGet);
            return result;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    public static String doPost(String url, Map<String, String> params) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(getUrlEncodedFormEntity(params));
        return execute(httpPost);
    }

    public static String execute(HttpRequestBase request) {
        StopWatch watch = new StopWatch();
        watch.start();
        CloseableHttpResponse response = null;
        try {
            response = defaultHttpPoolClient.execute(request);
            watch.stop();
            String requestURI = request.getURI().toString();
            logger.debug("http client:{} comleted use {} ms",requestURI,watch.getTotalTimeMillis());
            int status = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == status) {// 成功
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    String result = EntityUtils.toString(entity, DEFAULT_CHARSET);
                    EntityUtils.consume(entity);
                    return result;
                } else {
                    throw new ServiceException("请求无数据返回");
                }
            } else {
                throw new ServiceException("请求状态异常失败");
            }
        } catch (Exception e) {
            throw new ServiceException(request.getURI().toString() + "请求失败", e);
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("CloseableHttpResponse close error", e);
                }
            }
        }
    }

    private static UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, String> params) {
        UrlEncodedFormEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(getNameValuePair(params), DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
        }
        return entity;
    }

    private static List<NameValuePair> getNameValuePair(Map<String, String> params){
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if (null != params && !params.isEmpty()) {
            for (Entry<String, String> entry : params.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        return list;
    }

    public static void shutDown() {
        defaultHttpPoolClient.shutdown();
    }
}

 

ServiceException.java

package com.seezoon.framework.common.context.exception;

/**
 * 自定义异常方便后续扩展
 * 
 * @author hdf 2018年4月20日
 */
public class ServiceException extends RuntimeException {

    public ServiceException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public ServiceException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public ServiceException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

}

调用使用方法如下:

if (StringUtils.isNotEmpty(ip)) {
                    String ipInfo = HttpRequestUtils.doGet("http://ip.taobao.com/service/getIpInfo.php", Maps.newHashMap("ip",ip));
                    if (StringUtils.isNotEmpty(ipInfo)) {
                        JSONObject parseObject = JSON.parseObject(ipInfo);
                        if (parseObject.containsKey("data")) {
                            JSONObject data = parseObject.getJSONObject("data");
                            System.out.println(data.getString("region") + data.getString("city"));
                        }
                    }
                }

 

更详细的写在了CSDN上:https://blog.csdn.net/lr393993507/article/details/82345614

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中获取响应头中的IP地址可以通过以下方式实现。首先,您可以使用`HttpServletRequest`对象来获取请求的IP地址。在Spring Boot中,可以通过注入`HttpServletRequest`对象来获取它。然后,您可以使用`getHeader`方法来获取请求头中的IP地址。例如,以下代码片段展示了如何获取响应头中的IP地址: ```java @Autowired private HttpServletRequest request; public String getIpAddress() { String ipAddress = request.getHeader("X-Forwarded-For"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("HTTP_CLIENT_IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); } return ipAddress; } ``` 请注意,由于代理服务器的存在,请求头中的IP地址可能会被修改或隐藏。因此,上述代码中的`getIpAddress`方法尝试从多个请求头中获取IP地址,以确保获取到正确的IP地址。 引用\[1\]中的代码片段展示了如何使用`IpUtil`和`Ip2Region`来获取IP地址对应的省份信息。您可以根据实际情况进行调整和使用。 引用\[2\]中提到了一种使用网络API来查询IP地址归属地的方法。您可以使用淘宝IP地址库API或纯真IP地址库API来查询IP地址归属地。这些API提供了查询IP地址归属地的接口,您可以使用HTTP协议来调用这些接口,并从响应中解析出IP地址归属地。 引用\[3\]中提到了对比IP所在城市信息的步骤。通过获取发起支付时的IP和扫码时的IP,您可以使用IP对应的城市进行对比。目前市面上有很多通过IP获取城市的开放接口,您可以选择使用收费接口,如百度地图、高德地图,或者购买阿里云市场上的IP库来获取IP地址对应的城市信息。 综上所述,您可以使用上述方法来在Spring Boot中获取响应头中的IP地址,并根据需要进行IP地址归属地的查询和对比。 #### 引用[.reference_title] - *1* *3* [【支付系统】java springboot 通过ip获取所在地城市信息](https://blog.csdn.net/qq_39078783/article/details/131123898)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot获取IP归属地](https://blog.csdn.net/weixin_35756690/article/details/129453664)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值