java 服務端調用URL連接

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;


public class aaa {
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")));
      
      StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
      JSONObject json = JSONObject.parseObject(sb.toString());
      return json;
    } finally {
    is.close();//關閉流
    }
  }
  public static void main(String[] args) throws IOException, JSONException {
  String name = "廣州塔";
  //URLEncoder.encode(name, "UTF-8");   編碼字符集
  String dest_url = "http://api.map.baidu.com/place/v2/suggestion?query="+URLEncoder.encode(name, "UTF-8")+"&region=廣東省&output=json&ak=XdlkfbTXPDT2kzZluIFMwUUDGbEfXc5P";

    JSONObject json = readJsonFromUrl(dest_url);
    System.out.println(json.toString());
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章