Java retrieves json Objects Based on URLs

Source: Internet
Author: User

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 get json object according to the url * @ author openks * @ since 2013-7-16 * need to add java-json.jar to run */public class GetPlaceByIp {private static String re AdAll (Reader rd) throws IOException {StringBuilder sb = new StringBuilder (); 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, it can be seen from here that even if return is returned, it will still execute finally! ") ;}} Public static void main (String [] args) throws IOException, JSONException {// here call Baidu ip location api service for details see http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm JSONObject json = readJsonFromUrl (" http://api.map.baidu.com/location/ip? Ak = f454f8a5efe5e577997931cc01de00004 & ip = 202.198.16.3 "); System. out. println (json. toString (); System. out. println (JSONObject) json. get ("content ")). get ("address "));}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.