Java實現利用在線的API對IP地址進行解析(內部代碼分享)

很多人在做項目的時候會記錄用戶的IP,那麼要想展示的出來的話就需要把IP轉換成對應的地址纔可以,不然看着一串串數字鬼知道是那個地區的,轉成對應的地址一般有2種,一種是基於一些離線的數據庫進行解析和查找,另外一種是根據在線提供的API進行獲取,今天我們要說的是第二種方式,基於在線的API進行查找,下面我把代碼貼出來,不費話了。代碼涉及到了2個類,一個是發送網絡請求的,一個是獲取IP封裝的工具類。

HttpUtils

package com.yuxuan.utils;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;

public class HttpUtils {

	public static String httpRequest(String reqUrl) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(reqUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			httpUrlConn.setDoOutput(false);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();

		} catch (Exception e) {
			System.out.println(e.getStackTrace());
		}
		return buffer.toString();
	}


	public static String httpRequest(String reqUrl,String encoding) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(reqUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			httpUrlConn.setDoOutput(false);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encoding);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
			System.out.println(e.getStackTrace());
		}
		return buffer.toString();
	}
}

IpAddressUtils 

package com.yuxuan.utils;

import org.json.JSONObject;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.util.StringUtils;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Administrator
 */
public class IpAddressUtils {

	private static AtomicLong atomicLong = new AtomicLong(0);

	/**
	 * 通過IPws查詢
	 * @param ip
	 * @return
	 */
	private static String getIpWs126Net(String ip){
		try{
			String res = HttpUtils.httpRequest(String.format("http://ip.ws.126.net/ipquery?ip=%s", ip),"GBK");
			if(StringUtil.isNotBlank(res)){
				res = res.substring(res.indexOf("localAddress") + 13, res.length());
				JSONObject jsonObject = new JSONObject(res);
				String city = jsonObject.getString("city");
				String province = jsonObject.getString("province");
				if(city.equals(province)){
					return city;
				}
				return province+city;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通過IPAPI查詢
	 * @param ip
	 * @return
	 */
	private static String getIpAPI(String ip){
		try{
			String res = HttpUtils.httpRequest(String.format("http://ip-api.com/json/%s?lang=zh-CN", ip));
			if(!StringUtils.isEmpty(res)){
				JSONObject json = new JSONObject(res);
				String status = json.getString("status");
				if ("success".equals(status)) {
					String regionName = json.getString("regionName");
					String city = json.getString("city");
					if(regionName.equals(city)){
						return city;
					}
					return regionName + city;
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * whois.pconline.com.cn  太平洋IP爲最優選擇
	 * @param ip
	 * @return
	 */
	private static String getWhoisPconLineIp(String ip){
		try{
			String res = HttpUtils.httpRequest(String.format("http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true", ip),"GBK");
			if(!StringUtils.isEmpty(res)){
				JSONObject jsonObject = new JSONObject(res);
				String addr = jsonObject.getString("addr");
				return addr;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}


	private static String getAddressByIp(String ip){
		String addr = null;
		addr = getWhoisPconLineIp(ip);
		if(Objects.isNull(addr)){
			addr = getIpAPI(ip);
			if(Objects.isNull(addr)){
				addr = getIpWs126Net(ip);
				if(Objects.isNull(addr)){
					return null;
				}
			}
		}
		return addr;
	}


	public static boolean isInnerIP(String ipAddress){
		boolean isInnerIp = false;
		long ipNum = getIpNum(ipAddress);
		/**
		 私有IP:A類  10.0.0.0-10.255.255.255
		 B類  172.16.0.0-172.31.255.255
		 C類  192.168.0.0-192.168.255.255
		 當然,還有127這個網段是環回地址
		 **/
		long aBegin = getIpNum("10.0.0.0");
		long aEnd = getIpNum("10.255.255.255");
		long bBegin = getIpNum("172.16.0.0");
		long bEnd = getIpNum("172.31.255.255");
		long cBegin = getIpNum("192.168.0.0");
		long cEnd = getIpNum("192.168.255.255");
		isInnerIp = isInner(ipNum,aBegin,aEnd) || isInner(ipNum,bBegin,bEnd) || isInner(ipNum,cBegin,cEnd) || ipAddress.equals("127.0.0.1");
		return isInnerIp;
	}

	/**
	 * 判斷IP是否爲內網IP
	 * @param ipAddress
	 * @return
	 */
	private static long getIpNum(String ipAddress) {
		String [] ip = ipAddress.split("\\.");
		long a = Integer.parseInt(ip[0]);
		long b = Integer.parseInt(ip[1]);
		long c = Integer.parseInt(ip[2]);
		long d = Integer.parseInt(ip[3]);

		long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
		return ipNum;
	}

	private static boolean isInner(long userIp,long begin,long end){
		return (userIp>=begin) && (userIp<=end);
	}


	/**
	 * 外部調用
	 * @param ip
	 * @return
	 */
	public static String getAddressByIP(String ip){
		if(isInnerIP(ip)){
			return "內網IP";
		}else{
			return getAddressByIp(ip);
		}
	}

	public static void main(String[] args) {
		String ip = "47.92.102.22";
//		String res = getIpWs126Net("39.134.32.255");
//		String res = getIpAPI("39.134.32.255");
//		String res = getWhoisPconLineIp("47.92.102.22");
		String res = getAddressByIP(ip);
		System.out.println(res);
	}

}

以上就分享這麼多,更多幹貨請關注博客,每天更新哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章