原文地址https://blog.csdn.net/fanxiangru999/article/details/70147981
現在開發大部分都是服務化或者微服務,數據交換都是跨服務的,這裏記錄java調取其他接口的方法,java代碼如下:
- /**
- *
- *<p>類描述:接口讀取工具。</p>
- */
- public class ReadUrlUtil {
- 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);
- }
- String jsonText = sb.toString();
- JSONObject json = JSONObject.fromObject(jsonText);
- return json;
- } finally {
- is.close();
- }
- }
- }
測試代碼如下:
- public static void main(String[] args) throws IOException, JSONException {
- / 這裏調用百度的ip定位api服務 詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
- String ip = "113.57.244.100";
- String url = "http://api.map.baidu.com/location/ip?ak=32f38c9491f2da9eb61106aaab1e9739&ip="+ip+"&coor=bd09ll";
- JSONObject json = ReadUrlUtil.readJsonFromUrl(url);
- System.out.println(json.toString());
- System.out.println("經度:"+((JSONObject) json.get("content")).getJSONObject("point").get("x"));
- System.out.println("維度:"+((JSONObject) json.get("content")).getJSONObject("point").get("y"));
- String city =(String) ((JSONObject) json.get("content")).getJSONObject("address_detail").get("city");
- city = city.replace("市","");
- System.out.println(city);
- }