Android应用如何获取外网ip
国内有很多大厂有公开的接口:淘宝,搜狐等
我这里使用了搜狐的接口获取的IP地址。
http://pv.sohu.com/cityjson?ie=utf-8
返回结果:
var returnCitySN = {"cip": "223.227.152.81", "cid": "510100", "cname": "四川省成都市"};
然后把这个结果解析出来就可以了.
如何获取地理位置和运营商
ip地址作为参数,这里我用了淘宝的接口.
通过外网IP地址进行解析
http://ip.taobao.com/service/getIpInfo.php?ip=223.227.152.81
返回结果:
{
"code":0,
"data":{
"country":"中国",
"country_id":"CN",
"area":"西南",
"area_id":"500000",
"region":"四川省",
"region_id":"510000",
"city":"成都市",
"city_id":"510100",
"county":"",
"county_id":"-1",
"isp":"电信",
"isp_id":"100017",
"ip":"223.227.152.81"
}
}
通过GPS地理位置信息进行解析
没有使用这个方式。
用法
String target = HttpUtils.httpGetRequest("http://pv.sohu.com/cityjson?ie=utf-8", "UTF-8");
String ip = HttpUtils.parseIP(target);
String result = HttpUtils.httpGetRequest("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip, "GBK");
Log.i("TAG", "run: " + result);
HashMap<String,String> address = HttpUtils.parseAddress(result);
Log.e("TAG", "run: "+address.toString() );
代码
public class HttpUtils {
private static final int TIMEOUT_IN_MILLIONS = 5000;
public HttpUtils() {
}
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String httpGetRequest(String urlStr, String encode) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
BufferedReader bufferedReader = null;
InputStreamReader isr = null;
try {
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestMethod("GET");
// conn.setRequestProperty("host", "1212.ip138.com");
conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Cache-Control", "max-age=0");
conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");
conn.setInstanceFollowRedirects(false);
if (conn.getResponseCode() == 200) {
// is = conn.getInputStream();
// baos = new ByteArrayOutputStream();
// int len = -1;
// byte[] buf = new byte[128];
//
// while ((len = is.read(buf)) != -1) {
// baos.write(buf, 0, len);
// }
// baos.flush();
// return baos.toString();
String result = "";
isr = new InputStreamReader(conn.getInputStream(), encode);
bufferedReader = new BufferedReader(isr);
String line;
for (; (line = bufferedReader.readLine()) != null; ) {
result += "\n" + line;
}
return result;
} else {
android.util.Log.e("TAG", "httpGetRequest(): " + conn.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (isr != null){
isr.close();
}
if (bufferedReader != null){
bufferedReader.close();
}
} catch (IOException e) {
}
try {
if (baos != null)
baos.close();
if (isr != null){
isr.close();
}
if (bufferedReader != null){
bufferedReader.close();
}
} catch (IOException e) {
}
conn.disconnect();
}
return null;
}
/**
* 解析地址数据
*
* @param content
* @return
*/
public static HashMap<String, String> parseAddress(String content) {
HashMap<String, String> address = new HashMap();
if (!TextUtils.isEmpty(content)) {
// 处理返回的省市区信息
System.out.println(content);
String[] temp = content.split(",");
if (null == temp) {
return null;
}
int length = temp.length;
if (length < 3) {
return null;
}
String region = (temp[5].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);// 省份
String country = "";
String area = "";
String city = "";
String county = "";
String isp = "";
for (int i = 0; i < length; i++) {
switch (i) {
case 1:
country = (temp[i].split(":"))[2].replaceAll("\"", "");
country = decodeUnicode(country);// 国家
break;
case 3:
area = (temp[i].split(":"))[1].replaceAll("\"", "");
area = decodeUnicode(area);// 地区
break;
case 5:
region = (temp[i].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);// 省份
break;
case 7:
city = (temp[i].split(":"))[1].replaceAll("\"", "");
city = decodeUnicode(city);// 市区
break;
case 9:
county = (temp[i].split(":"))[1].replaceAll("\"", "");
county = decodeUnicode(county);// 地区
break;
case 11:
isp = (temp[i].split(":"))[1].replaceAll("\"", "");
isp = decodeUnicode(isp); // ISP公司
break;
}
}
if (!TextUtils.isEmpty(country))
address.put("country", country);
if (!TextUtils.isEmpty(area))
address.put("area", area);
if (!TextUtils.isEmpty(region))
address.put("region", region);
if (!TextUtils.isEmpty(city))
address.put("city", city);
if (!TextUtils.isEmpty(county))
address.put("county", county);
if (!TextUtils.isEmpty(isp))
address.put("isp", isp);
return address;
}
return null;
}
/**
* unicode 转换成 中文
*
* @param content
* @return
* @author fanhui 2007-3-15
*/
public static String decodeUnicode(String content) {
if (TextUtils.isEmpty(content)) {
return "";
}
char c;
int len = content.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len; ) {
c = content.charAt(x++);
if (c == '\\') {
c = content.charAt(x++);
if (c == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
c = content.charAt(x++);
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + c - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + c - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + c - 'A';
break;
default:
throw new IllegalArgumentException("Malformed encoding.");
}
}
outBuffer.append((char) value);
} else {
if (c == 't') {
c = '\t';
} else if (c == 'r') {
c = '\r';
} else if (c == 'n') {
c = '\n';
} else if (c == 'f') {
c = '\f';
}
outBuffer.append(c);
}
} else {
outBuffer.append(c);
}
}
return outBuffer.toString();
}
/**
* 解析IP地址
* 从IP地址的返回信息中解析出来ip
*
* @param content
* @return
*/
public static String parseIP(String content) {
if (TextUtils.isEmpty(content))
return null;
String ip = "";
if (content.contains("{") && content.contains("}")) {
int start = content.indexOf("{");
int end = content.indexOf("}") + 1;
String target = content.substring(start, end);
android.util.Log.i("TAG", "run: " + content);
try {
JSONObject json = new JSONObject(target);
ip = (String) json.get("cip");
} catch (Exception e) {
android.util.Log.e("TAG", "parseIP: ", e);
}
}
Log.i("TAG", "run: " + ip);
return ip;
}
}
为什么要获取用户当前的地理位置信息?
需求.