百度API_Demo

package com.test.www;

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;

/**
 * @author QQ: 1236897
 *
 */
public class BaidDuApiDemo {
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static String 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 jsonText;
        } finally {
            is.close();
            // System.out.println("同时 从这里也能看出 即便return了,仍然会执行finally的!");
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String json = null;
        String ak="";
        try {
            json = readJsonFromUrl("http://api.map.baidu.com/place/v2/search?query=小学&region=广州&output=json&ak=");
            //json = readJsonFromUrl("http://api.map.baidu.com/geocoder/v2/?address=广州高德置地&output=json&ak=");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(json);
//        System.out.println(((JSONObject) json.get("content")).get("address"));
    }

}
原文地址:https://www.cnblogs.com/MarchThree/p/5208611.html