Java调用淘宝Ip库返回城市

/**
*功能说明:根据Ip获取设备归属地
* @param ip
* @return
*/
public String getIP(String ip) {
String city = "";
try {
DefaultHttpClient hc = new DefaultHttpClient();
InputStream is = null;
HttpGet http_get = new HttpGet(
"http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
HttpEntity e = hc.execute(http_get).getEntity();
is = e.getContent();
StringWriter sw = new StringWriter();
IOUtils.copy(is, sw);
is.close();
String res = sw.toString();
try {
JSONObject resp = new JSONObject(res);
if (resp.has("data")) {
JSONObject data = resp.getJSONObject("data");
if (data.has("city")) {
city = data.getString("city");
}
}

} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return city;
}

你可能感兴趣的:(java)