The data returned by Taobao is:
{"Code": 0, "data": {"Country": "\U4E2D\U56FD", "country_id": "CN", "area": "\u534e\u4e1c", "area_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"}}
Usage:
Copy Code code as follows:
String arr1 = Getaddressbyip.getaddressbyip ("120.192.182.1");
System.out.println (ARR1);
Please see the code in detail
Copy Code code as follows:
Package Getaddressbyip;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Net.sf.json.JSONObject;
public class Getaddressbyip
{
/**
*
* @param IP
* @return
*/
public static string Getaddressbyip (String IP) {
String resout = "";
try{
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 ("area") + "--" +obj2.get ("City") + "--" +obj2.get ("ISP");
}else{
Resout = "Incorrect IP address";
}
}catch (Exception e) {
E.printstacktrace ();
Resout = "Get IP address exception:" +e.getmessage ();
}
return resout;
}
public static string Getjsoncontent (String urlstr)
{
Try
{//Get HttpURLConnection Connection object
URL url = new URL (urlstr);
HttpURLConnection httpconn = (httpurlconnection) URL
. OpenConnection ();
Setting connection Properties
Httpconn.setconnecttimeout (3000);
Httpconn.setdoinput (TRUE);
Httpconn.setrequestmethod ("get");
Get the corresponding code
int respcode = Httpconn.getresponsecode ();
if (Respcode = 200)
{
Return Convertstream2json (Httpconn.getinputstream ());
}
}
catch (Malformedurlexception e)
{
E.printstacktrace ();
}
catch (IOException E)
{
E.printstacktrace ();
}
Return "";
}
private static String Convertstream2json (InputStream inputstream)
{
String jsonstr = "";
Bytearrayoutputstream equivalent to memory output stream
Bytearrayoutputstream out = new Bytearrayoutputstream ();
byte[] buffer = new byte[1024];
int len = 0;
Transfer the input stream to the memory output stream
Try
{
while (len = inputstream.read (buffer, 0, buffer.length))!=-1)
{
Out.write (buffer, 0, Len);
}
Converts a memory stream to a string
Jsonstr = new String (Out.tobytearray ());
}
catch (IOException E)
{
TODO auto-generated Catch block
E.printstacktrace ();
}
return jsonstr;
}
}