mavenJSON包导入配置:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
如果没有用maven则需要手动导入jar包:json.jar
package com.company.item.util;
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 org.json.JSONObject;
/**
* 根据IP地址获取用户当前登录的地址信息
* @Copyright (C),沪友科技
* @author zt
* @Date:2016年3月28日
*/
public class AddressUtils {
/*
* 参数含义:
* dataURL :访问的接口路径
* ip :ip地址
* encodingString:所访问接口规定的字符集编码
*/
/*传入相关参数返回一个JSONObject组织的地址数据*/
public static JSONObject getAddrMessage(String dataURL,String ip, String encodingString)
throws UnsupportedEncodingException {
String returnStr = getAreaDatas(dataURL, ip, encodingString);
System.out.println(returnStr);
if (returnStr != null) {
/*接口返回的json类型字符串转换为JSON可以直接被转换为相应的中文地址*/
JSONObject jsonb = new JSONObject(returnStr);
String[] temp = returnStr.split(",");
if(temp.length<3){
return jsonb.put("msg", "IP地址无效");
}
return jsonb;
}
return null;
}
/*访问接口;接收返回数据*/
private static String getAreaDatas(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
/*通过接口路径,创建HTTP连接对象*/
connection = (HttpURLConnection) url.openConnection();
/*连接对象的一些属性配置*/
connection.setConnectTimeout(2000);//连接超时时间,单位毫秒
connection.setReadTimeout(2000);//读取数据超时时间,单位毫秒
connection.setDoOutput(true);//是否打开输出流 true|false
connection.setDoInput(true);//是否打开输入流true|false
connection.setRequestMethod("POST");//提交方法POST|GET
connection.setUseCaches(false);//是否缓存true|false
connection.connect();// 打开连接端口
/*数据交互对象流(向接口提供服务器方发送数据请求)*/
DataOutputStream out = new DataOutputStream(connection.getOutputStream());//打开输出流往对端服务器写数据
out.writeBytes(content);// 写数据
out.flush();// 刷新
out.close();// 关闭输出流
/*通过缓冲字符流接收服务器返回的数据*/
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();// 关闭连接
}
}
return null;
}
/*如果没用JSONObject对象则可以通过这个方法进行对应字段unicode码转中文*/
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();
}
/*
* 相关主要字段
* {"country":"\u4e2d\u56fd", 国家 country
* "country_id":"CN",
* "area":"\u897f\u5357", 大地区 area
* "area_id":"500000",
* "region":"\u56db\u5ddd\u7701", 省份 region
* "region_id":"510000",
* "city":"\u6210\u90fd\u5e02", 城市 city
* "city_id":"510100",
* "county":"", 市区 county
* "county_id":"-1",
* "isp":"\u7535\u4fe1", 网络(电信/网通/其他) isp
* "isp_id":"100017",
* "ip":"118.123.249.159"}
* }
*/
public static void main(String[] args) {
AddressUtils addressUtils = new AddressUtils();
// 测试ip 219.136.134.157 118.123.249.159
String ip = "219.136.134.157";
/*接口URL网络上有很多种*/
String dataURL = "http://ip.taobao.com/service/getIpInfo.php";
String address = "";
try {
/*这里要注意有一个坑的地方:传IP这个的时候 要传"ip="+ip这种规则进行传参否则获取不到正确的数据*/
JSONObject jsonb = getAddrMessage(dataURL,"ip="+ip,"utf-8");
/*封装为JSON数据更方便处理*/
System.out.println(jsonb.getJSONObject("data").getString("region"));
System.out.println(jsonb.getJSONObject("data").getString("isp"));
/*
System.out.println(addressUtils.decodeUnicode("\u4e2d\u56fd"));
System.out.println(addressUtils.decodeUnicode("\u897f\u5357"));
System.out.println(addressUtils.decodeUnicode("\u56db\u5ddd\u7701"));
System.out.println(addressUtils.decodeUnicode("\u6210\u90fd\u5e02"));
System.out.println(addressUtils.decodeUnicode("\u8d8a\u79c0\u533a"));
System.out.println(addressUtils.decodeUnicode("\u7535\u4fe1"));
*/
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}