Java obtains physical address according to IP address (through Baidu API interface)

Keywords: Programming Java Apache encoding Android

1. Download and import the dependency package of 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

Baidu online disk link: https://pan.baidu.com/s/1aNBeVvaSm7ePZ3pDH3HeAA 
Extraction code: d8tr

2. Create application in Baidu map;

(1) Click the application management on the left - > my application - > click the create application button, select the type of project according to the demand, fill in the white list as unrestricted temporarily, and then change it to domain name

(2) After filling in, click submit to get an AK (Java code needs to be used later) on the interface as shown in the figure below;

3. Create a Java tool class IpAddressUtil;

4. Write the following code:

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) {
		// Create default http connection
		HttpClient client = HttpClients.createDefault();
		// Create a post request
		HttpPost post = new HttpPost("http://api.map.baidu.com/location/ip");
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		// Parameters passed
		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 {
			// Put the parameter into the request entity after transcoding
			HttpEntity entitya = new UrlEncodedFormEntity(paramList, "utf-8");
			post.setEntity(entitya);// Put the request entity in the post request
			// Use http connection to execute get request and get http response
			HttpResponse response = client.execute(post);
			// Get response entity from response
			HttpEntity entity = response.getEntity();
			// Convert response entity to text
			String str = EntityUtils.toString(entity);
			
			// Partition analysis
			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;
	}
    
	// test
	public static void main(String[] args) throws IOException {
		IpAddressUtil ipAddressUtil = new IpAddressUtil();
		String ip = "59.42.239.26";
		System.out.println(ipAddressUtil.getAddressResult(ip));
	}
}

5. Call where you need to call:

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

6. Advantages and disadvantages of Baidu API interface:

Advantages: calling Baidu API interface will save faster than Taobao API, with fewer error reporting times.

Disadvantages:

(1) The AK of Baidu API is different according to the project type (browser, Android, wechat, etc.);

(2) Baidu API only supports the resolution of domestic IP address, but cannot;

(3) Baidu API development and use is more troublesome than Taobao API.

Posted by todd2006 on Tue, 07 Apr 2020 09:37:37 -0700