Java根据IP地址获取物理地址(通过百度API接口)

原创
2020/04/07 17:41
阅读数 1.5K

1. 下载并导入HttpClient的依赖包:

httpmime-4.5.2.jar

httpcore-4.4.4.jar

httpclient-win-4.5.2.jar

httpclient-cache-4.5.2.jar

httpclient-4.5.2.jar

百度网盘链接:https://pan.baidu.com/s/1aNBeVvaSm7ePZ3pDH3HeAA 
提取码:d8tr

2. 在百度地图里面创建应用;

(1)点击左边应用管理—>我的应用—>点击创建应用按钮,按需求选择项目的类型,白名单部分暂时填写为不受限制即可,到时候改为域名那个即可

(2)填写完,点击提交,就可以在如下图所示的界面上获取到一个AK(后面Java代码需要用);

3.  创建一个Java工具类IpAddressUtil

4. 写入以下代码:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class IpAddressUtil {

	public static String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
							case '0':
							case '1':
							case '2':
							case '3':
							case '4':
							case '5':
							case '6':
							case '7':
							case '8':
							case '9':
								value = (value << 4) + aChar - '0';
								break;
							case 'a':
							case 'b':
							case 'c':
							case 'd':
							case 'e':
							case 'f':
								value = (value << 4) + 10 + aChar - 'a';
								break;
							case 'A':
							case 'B':
							case 'C':
							case 'D':
							case 'E':
							case 'F':
								value = (value << 4) + 10 + aChar - 'A';
								break;
							default:
								throw new IllegalArgumentException("Malformed encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					outBuffer.append(aChar);
				}
			} else {
				outBuffer.append(aChar);
			}
		}
		return outBuffer.toString();
	}
	
	public static String getAddressResult(String ip) {
		// 创建默认http连接
		HttpClient client = HttpClients.createDefault();
		// 创建一个post请求
		HttpPost post = new HttpPost("http://api.map.baidu.com/location/ip");
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		// 传递的参数
		paramList.add(new BasicNameValuePair("ip", ip));
		paramList.add(new BasicNameValuePair("ak", "XXX"));
		paramList.add(new BasicNameValuePair("sn", ""));
		paramList.add(new BasicNameValuePair("coor", ""));
		
		String address = "";
		try {
			// 把参转码后放入请求实体中
			HttpEntity entitya = new UrlEncodedFormEntity(paramList, "utf-8");
			post.setEntity(entitya);// 把请求实体放post请求中
			// 用http连接去执行get请求并且获得http响应
			HttpResponse response = client.execute(post);
			// 从response中取到响应实体
			HttpEntity entity = response.getEntity();
			// 把响应实体转成文本
			String str = EntityUtils.toString(entity);
			
			// 分隔解析
			if(str.length() >0) {
				int index = str.indexOf("province");
				int index2 = str.indexOf("city");
				int index3 = str.indexOf("district");
				String province = str.substring(index+11, index2-3);
				String city = str.substring(index2+7, index3-3);
				// System.out.println(province);
				// System.out.println(city);
				address = decodeUnicode(province) + "," + decodeUnicode(city);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return address;
	}
    
	// 测试
	public static void main(String[] args) throws IOException {
		IpAddressUtil ipAddressUtil = new IpAddressUtil();
		String ip = "59.42.239.26";
		System.out.println(ipAddressUtil.getAddressResult(ip));
	}
}

注意:在getAddressResult() 方法中paramList.add(new BasicNameValuePair("ak", "XXX"));传递的参数是调用百度API所用的AK,即上述第2步获取得到的AK,把XXX改为你项目的AK即可。

5. 在需要调用的地方调用:

public void userLogin(String userName, String password, 
		HttpServletRequest request, HttpServletResponse response) 
			throws IOException {
    ......
    String address = "";
    if(ip.length() > 0) {
        address = IpAddressUtil.getAddressResult(ip);
    }
    ......
}

6. 百度API接口优缺点:

优点:调用百度API接口较淘宝API解救速度会更快,报错次数少

缺点:

(1)百度API的AK根据项目类型(浏览器端、安卓端、微信端等)不同;

(2)百度API只支持解析国内IP地址,解析不了;

(3)百度API开发使用较淘宝API而言很麻烦

注意:在测试时,百度API的AK可以不受限制,但当项目正式上线时,需要在创建应用获取AK的白名单那里改为域名。

7. 传送门:

通过Java获取IP地址: https://my.oschina.net/u/3986411/blog/3223248

Java根据IP地址获取物理地址(通过淘宝API接口): https://my.oschina.net/u/3986411/blog/3223276

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部