Copy Code code as follows:
Package test;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.Reader;
Import Java.net.URL;
Import Java.nio.charset.Charset;
Import org.json.JSONException;
Import Org.json.JSONObject;
/**
* Java gets JSON object from URL
* @author Openks
* @since 2013-7-16
* Need to add Java-json.jar to run
*/
public class Getplacebyip {
private static String ReadAll (Reader Rd) throws IOException {
StringBuilder sb = new Strin Gbuilder ();
int cp;
while (cp = Rd.read ())!=-1) {
sb.append ((char) CP);
}
return sb.tostring ();
}
public static jsonobject readjsonfromurl (String url) throws IOException, jsonexception {
InputStream is = new URL (URL). OpenStream ();
try {
BufferedReader rd = new BufferedReader (new InputStreamReader (IS, Charset.forname ("UTF-8"));
String jsontext = readall (RD);
jsonobject json = new Jsonobject (jsontext);
return JSON;
} finally {
is.close ();
//System.out.println ("at the same time from here also can see that even if return, will still execute finally!" ");
}
}
public static void Main (string[] args) throws IOException, Jsonexception {
Here call Baidu's IP Location API service details see http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
Jsonobject json = Readjsonfromurl ("http://api.map.baidu.com/location/ip?ak=f454f8a5efe5e577997931cc01de3974& ip=202.198.16.3 ");
System.out.println (Json.tostring ());
System.out.println ((jsonobject) json.get ("Content")). Get ("address");
}
}