Java Call Baidu Positioning API service to obtain geographic location example _java

Source: Internet
Author: User

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");
}
}


Related Article

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.