需求:由于项目需求,需要获取用户手机外网IP。
这里是用到搜狐的IP地址查询接口,如下:
搜狐IP地址查询接口(默认GBK):http://pv.sohu.com/cityjson
搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/cityjson?ie=utf-8
返回json如下:
var returnCitySN = {"cip": "210.22.130.114", "cid": "310000", "cname": "上海市"};
这里的话,我这里就直接开启线程,获取手机的IP:
代码如下:
//获取手机外网IP
new Thread(new Runnable() {
@Override
public void run() {
URL infoUrl = null;
InputStream inStream = null;
String line = "";
try {
infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
URLConnection connection = infoUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inStream = httpConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
// 从反馈的结果中提取出IP地址
int start = strber.indexOf("{");
int end = strber.indexOf("}");
String json = strber.substring(start, end + 1);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
line = jsonObject.optString("cip");
MLog.e("ip", "ip==========================" + line);
} catch (JSONException e) {
e.printStackTrace();
}
}
SPUtils.putString(Constant.IP, line);
}
} catch (Exception e) {
e.printStackTrace();
//拿不到IP的情况,给个默认值
SPUtils.putString(Constant.IP, "192.168.1.1");
}
}
}).start();