Preface
Most of the developments are now service-oriented or micro-services, and data exchanges are cross-services. Here we record the methods of Java to retrieve other interfaces. I won’t say much about it below. Let’s take a look at the detailed introduction together.
The java code is as follows:
/** * *<p>Class Description: Interface Reading Tool. </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(); } } }The test code is as follows:
public static void main(String[] args) throws IOException, JSONException { / For details of the IP location API service that calls Baidu here, please refer to 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("Longitude: "+((JSONObject) json.get("content")).getJSONObject("point").get("x")); System.out.println("Dimension: "+((JSONObject) json.get("content")).getJSONObject("point").get("y")); String city =(String) ((JSONObject) json.get("content")).getJSONObject("address_detail").get("city"); city = city.replace("city",""); System.out.println(city); }The test results are shown below:
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.