需求:由于项目需求,需要获取用户手机外网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();
因项目需求,需获取用户手机外网IP。使用搜狐的IP地址查询接口,包括默认GBK编码和可设置编码的接口,返回json数据。通过开启线程获取手机IP,并给出了相应代码。
2346

被折叠的 条评论
为什么被折叠?



