Данные, возвращаемые Taobao:
{"code": 0, "data": {"country": "/u4e2d/u56fd", "country_id": "cn", "rea": "/u534e/u4e1c", "rea_id": "300000" "Region": "/u5c71/u4e1c/u7701", "Region_id": " 370000 "," City ":"/u4e1c/u8425/u5e02 "," city_id ":" 370500 "," County ":" "," County_id ":"-1 "," ISP ":"/U8054/U901A " , "ISP_ID": "100026", "IP": "60.214.183.158"}}
Использование:
Кода -копия выглядит следующим образом:
String arr1 = getAddressbyip.getaddressbyip ("120.192.182.1");
System.out.println (arr1);
Пожалуйста, обратитесь к коду для деталей
Кода -копия выглядит следующим образом:
Пакет GetAddressbyip;
импортировать java.io.bytearrayoutputstream;
импортировать java.io.ioexception;
импортировать java.io.inputstream;
Импорт java.net.httpurlConnection;
Импорт java.net.malformedurlexception;
импортировать java.net.url;
Импорт net.sf.json.jsonobject;
Общедоступный класс GetAddressbyip
{
/**
*
* @param ip
* @возвращаться
*/
public Static String getAddressbyip (String ip) {
String resout = "";
пытаться{
String str = getJsonContent ("http://ip.taobao.com/service/getipinfo.php?ip="+ip);
System.out.println (str);
JsonObject obj = jsonObject.fromObject (str);
JsonObject obj2 = (jsonObject) obj.get ("data");
String Code = (String) obj.get ("code");
if (code.equals ("0")) {
RESout = obj2.get ("country") +"-" +obj2.get ("rea") +"-" +obj2.get ("city") +"-" +obj2.get ("ISP ");
}еще{
Resout = «IP -адрес неверный»;
}
} catch (Exception e) {
e.printstacktrace ();
RESOLVE = "GET IP -адрес Exception:"+e.getMessage ();
}
вернуть ответ;
}
Public Static String GetJsonContent (String urlstr)
{
пытаться
{// Получить объект подключения httpurlConnection
Url url = new URL (urlstr);
Httpurlconnection httpconn = (httpurlconnection) URL
.openconcection ();
// установить свойства соединения
httpconn.setconnecttimeout (3000);
httpconn.setDoinput (true);
httpconn.setrequestmethod ("Get");
// Получить соответствующий код
int respcode = httpconn.getresponsecode ();
if (respcode == 200)
{
return ConvertStream2json (httpconn.getInputStream ());
}
}
Улов (Malformedurlexception e)
{
e.printstacktrace ();
}
поймать (ioException e)
{
e.printstacktrace ();
}
возвращаться "";
}
Private Static String Converstream2Json (InputStream InputStream)
{
String jsonstr = "";
// BytearRayOutputStream эквивалентен выводу памяти
BytearRayOutputStream OUT = New BytearRayOutputStream ();
Byte [] buffer = новый байт [1024];
int len = 0;
// Передача входного потока в выходной поток памяти
пытаться
{
while ((len = inputstream.read (buffer, 0, buffer.length))! = -1)
{
out.write (буфер, 0, Лен);
}
// конвертировать поток памяти в строку
jsonstr = new String (out.tobytearray ());
}
поймать (ioException e)
{
// Todo Auto Generated Catch Blach
e.printstacktrace ();
}
вернуть JSonstr;
}
}