Main ideas:

Obtain the IP address of the visitor through request. 2. Obtain the name of the city where the IP address resides by invoking the external interface through the IP address. 3. After obtaining the city name, the external interface (weather) is called again with the city name as a parameter to obtain the weather information of the city.

Of course, how can we know the city and weather of the IP address by ourselves? We still rely on the interface. Of course, this interface site offers many other useful and free interfaces, and the reason for using it is that it is easier to use than the other interface sites.

1. For general operation, come here to register and log in

2. Log in and add an interface(There may also be a range of email authentication and other identifiers, which I won’t go into here.) Click on the API and filter the type (free) as shown below:We want to achieve the function is [IP address] [weather forecast] these two interfaces. Click on each of them and jump to the next page – apply now – that’s it. After applying, click on the upper right – Personal Center – > Click – My Interface -. As shown in figure:In my interface, you can see what interfaces you have applied for. The picture below contains some of my other interfaces. I will not take screenshots of that one. 3 Test the interfaceClick test on the back of the interface and we can go and test it for ourselvesTake the IP address 223.104.212.171 as an example. This is an IP address in Shanghai. The default values are the main ones.The result is as follows:

If resultCode :200 is displayed in the RETURNED JSON, the request is successful and the city name is successfully obtained using the IP address. In accordance with our thinking, the weather information of Shanghai was obtained according to the city name. As with IP, test the weather forecast interface, as shown in the figure below:After filling in the Shanghai request, you can pull out your phone and check to see if the weather information is correct.The image above shows the weather forecast for the next few days, but it’s too long for me to capture all of it.

The above interface test is basically completed. Next, we start to use Java to solve the first problem. The IP address we obtained through request is not rigorous enough. Therefore, a piece of code is used to parse the IP first to obtain his real IP address. Create a new Class and name it IPUtil(you can also name it yourself)

import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; public class IpUtil { public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; try { ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); If (ipaddress. equals("127.0.0.1")) {InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); }} // In the case of multiple proxies, the first IP address is the real IP address of the client, and multiple IP addresses are split according to ',' if (ipAddress! = null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress =  ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { ipAddress=""; } // ipAddress = this.getRequest().getRemoteAddr(); return ipAddress; }}Copy the code

As you can see, this class converts the HttpServletRequest Request into an ipAddress and returns it. We continue to call the weather forecast interface with this ipAddress. By the way, we will use this tool class to capture the real IP address of all external access requests, so as to ensure that our visitors really see the weather of his city, instead of seeing the weather of the south in the north.

Let’s leave the problem of getting real IP above and test our interface. Create a new APIUtil class to test our interface code (some of the called utility class code is attached at the end of this article). The APIUtil mainly contains getCityByIP() and getWeatherByCity() as the main methods we call.

Public static void main(String[] args) {String ipAddress = "223.104.212.171"; String city = getCityByIP(ipAddress); System.out.println(" get city name: "+city); } private static String getCityByIP(String IP) {String city =""; String jsonStr = ""; String strUrl = "http://apis.juhe.cn/ip/ipNew"; String srtVlaue = "ip="+IP+"&key=022287affefd4e498740d2d107efbe4c"; jsonStr = HttpGetPost.sendGet(strUrl,srtVlaue); System.out.println(jsonStr); If (jsonstr.equals (" timeout ")) {return "failed to get city name "; } JSONObject json = JSONObject.fromObject(jsonStr); String resultcode = (String) json.get("resultcode"); JSONObject result = (JSONObject) json.get("result"); if(resultcode.equals("200")) { city = (String) result.get("City"); }else {city = "city failed to get "; } if(city. Contains (" city ")) {city = city. Substring (0, 2); } system.out. println(" based on IP:"+IP+" get city name :"+city); return city; } private static Map<String,Object> getWeatherByCity(String City) {Map<String,Object> hashMap = new HashMap<String, Object>(); String jsonStr = ""; String strUrl = "http://apis.juhe.cn/simpleWeather/query"; String srtVlaue = "city="+City+"&key=93e7573d94a0b85b2ac38ded5aef41e0"; jsonStr = HttpGetPost.sendGet(strUrl,srtVlaue); System.out.println(jsonStr); JSONObject json = JSONObject.fromObject(jsonStr); String reason = (String) json.get("reason"); If (reason.equals(" query successful! )) { hashmap = JsonUtil.parseJSONstr2Map(jsonStr); } else {hashmap. Put (" error_code ", "get" + City + "weather failure"); } return hashmap; }Copy the code

Assuming that the IP address is 223.104.212.171, we first use getCityByIP() to obtain the city “Shanghai” corresponding to address 223.104.212.171. Then call getWeatherByCity() to get the weather information of the city “Shanghai” and display it in the Console, so that we can check whether the weather information is successfully obtained.

The running results are shown as follows:From the Console, we can see that the corresponding city of the IP address 223.104.212.171 is Shanghai. The API returns a series of JSON strings: {” the resultcode “:” 200 “, “” reason” : “query success”, “result” : {” Country “:” Chinese “, “Province”, “Shanghai”, “City”, “Shanghai”, “Isp” : “mobile”}, “error_code” : 0}.

Next, we will catch the City program as a parameter to call getWeatherByCity(City) this method, used to get the weather information of “Shanghai”. The code to change the main method is as follows:

Public static void main(String[] args) {String ipAddress = "223.104.212.171"; String city = getCityByIP(ipAddress); // system.out. println(" get city name: "+city); Map<String,Object> weather = getWeatherByCity(city); System.out.println(weather.toString()); }Copy the code

The running results are shown as follows:

Through “Shanghai “(city parameter), we call API to get the weather of the city. The third party API actually provides us with such an interface call: apis.juhe.cn/simpleWeath… It contains the weather for that day and the weather for the next few days, which we can also see from the JSON.

{"reason":" Query successful!" , "result" : {" city ", "Shanghai", "realtime" : {" temperature ":" 16 "and" humidity ":" 33 ", "info" : "cloudy", "wid" : "01", "direct" : "west wind", "power" : "2", 31 "aqi" : ""}," future ": [{" date" : "2020-03-16", "temperature" : "9 \ / 16 ℃", "weather" : "cloudy turn Yin", "wid" : {" day ":" 01 ", "night" : "02"}, "dire Ct ":" east wind "}, {" date ":" 2020-03-17 ", "temperature", "11 and 18 ℃ /", "weather" : "Yin" and "wid" : {" day ":" 02 ", "night" : "02"}, "direct" : "south"}, {" The date ":" 2020-03-18 ", "temperature" : "12 \ / 21 ℃", "weather" : "cloudy clears", "wid" : {" day ":" 01 ", "night" : "00"}, "direct" : "the southwester 23"}, {" date: "" The 2020-03-19 ", "temperature", "10 \ / 21 ℃", "weather" : "cloudy", "wid" : {" day ":" 01 ", "night" : "01"}, "direct" : "the north wind turns southeast wind"}, {" date ":" 2020-03-2 0 ", "temperature", "13 \ / 20 ℃", "weather", "qing", "wid" : {" day ":" 00 ", "night" : "00"}, "direct" : ""}}]," the south wind error_code: 0}"Copy the code

After that, you can wrap the retrieved parameters Map<String,Object> weather into a bean that you want to display on the front page. For example:

package com.wangyang.web.vo; public class Weather { private String City; private String Aqi; private String Direct; private String Futureweather; private String Humidity; private String Info; private String Power; private String Temperature; private String WeatherImgUrl; public Weather() { super(); } public Weather(String city, String aqi, String direct, String futureweather, String humidity, String info, String power, String temperature, String weatherImgUrl) { super(); City = city; Aqi = aqi; Direct = direct; Futureweather = futureweather; Humidity = humidity; Info = info; Power = power; Temperature = temperature; WeatherImgUrl = weatherImgUrl; } public String getCity() { return City; } public void setCity(String city) { City = city; } public String getAqi() { return Aqi; } public void setAqi(String aqi) { Aqi = aqi; } public String getDirect() { return Direct; } public void setDirect(String direct) { Direct = direct; } public String getFutureweather() { return Futureweather; } public void setFutureweather(String futureweather) { Futureweather = futureweather; } public String getHumidity() { return Humidity; } public void setHumidity(String humidity) { Humidity = humidity; } public String getInfo() { return Info; } public void setInfo(String info) { Info = info; } public String getPower() { return Power; } public void setPower(String power) { Power = power; } public String getTemperature() { return Temperature; } public void setTemperature(String temperature) { Temperature = temperature; } public String getWeatherImgUrl() { return WeatherImgUrl; } public void setWeatherImgUrl(String weatherImgUrl) { WeatherImgUrl = weatherImgUrl; } @Override public String toString() { return "Weather [City=" + City + ", Aqi=" + Aqi + ", Direct=" + Direct + ", Futureweather=" + Futureweather + ", Humidity=" + Humidity + ", Info=" + Info + ", Power=" + Power + ", Temperature=" + Temperature + ", WeatherImgUrl=" + WeatherImgUrl + "]"; }}Copy the code

Going back to the original issue of getting the real IP, this method is referenced in other posts: link: blog.csdn.net/yulei_qq/ar…

import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; public class IpUtil { public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; try { ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); If (ipaddress. equals("127.0.0.1")) {InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); }} // In the case of multiple proxies, the first IP address is the real IP address of the client, and multiple IP addresses are split according to ',' if (ipAddress! = null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress =  ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { ipAddress=""; } // ipAddress = this.getRequest().getRemoteAddr(); return ipAddress; }}Copy the code

In real development, this method can be used to filter request requests to obtain real IP addresses (which works in most cases).

At this point, basic method calls and usage are OK. Attached is my personal Blog homepage (Weikisa’s Blog) which contains a display of the weather call, if you are interested, you can try it. Although it is a simple API call, but in the actual development will also encounter a lot of problems, step by step error correction learning, I believe will also bring you a lot of harvest.

1.HttpGetPost: a common interface call tool based on the HTTP hypertext transfer protocol. You can also use HttpClient or something you’re familiar with.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; Public class HttpGetPost {/** * @param URL * @param URL * @param param * request parameters, The request parameters should be of the form name1= Value1&name2 =value2. Public static String sendGet(String URL, String param) {String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); URLConnection connection = realurl.openConnection (); connection.setConnectTimeout(3000); / / set the request of the general properties connection. The setRequestProperty (" accept ", "* / *"); connection.setRequestProperty("connection", "Keep-Alive"); Connection. The setRequestProperty (" the user-agent ", "Mozilla / 4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // Establish the actual connection connection.connect(); / / get all the response header field Map < String, a List < String > > Map = connection. GetHeaderFields (); For (String key: map.keyset ()) {system.out.println (key + "-- >" + map.get(key)); } / / define BufferedReader response in the input stream to read the URL = new BufferedReader (new InputStreamReader (connection. The getInputStream ())); String line; while ((line = in.readLine()) ! = null) { result += line; }} catch (Exception e) {system.out.println + e); e.printStackTrace(); Return "Request timed out "; } // Use the finally block to close the input stream finally {try {if (in! = null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * send a POST request to the specified URL ** @param URL * @param param * Request parameters, which should be of the form name1=value1&name2=value2. Public static String sendPost(String URL, String param) {PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realurl.openConnection (); conn.setConnectTimeout(10000); // Set the generic request property conn.setrequestProperty (" Accept ", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); Conn. SetRequestProperty (" the user-agent ", "Mozilla / 4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // To send a POST request, the following two lines must be set: conn.setdoOutput (true); conn.setDoInput(true); Out = new PrintWriter(conn.getOutputStream()); Out.print (param); // Flush the buffer of the output stream out.flush(); In = new BufferedReader(new InputStreamReader(conn.getinputStream ())); String line; while ((line = in.readLine()) ! = null) { result += line; }} catch (Exception e) {system.out.println (" error sending POST request! +e); e.printStackTrace(); } // Use finally blocks to close output streams, input streams finally{try{if(out! =null){ out.close(); } if(in! =null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; }}Copy the code

2.JsonUtil: contains methods for converting JSON to Map and HashMap data structures to obtain key-value values in JSON.

import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.util.*; Public class JsonUtil {public class JsonUtil {public class JsonUtil {public class JsonUtil {public class JsonUtil {public class JsonUtil { Object> parseJSON2Map(JSONObject json) { Map<String, Object> map = new HashMap<String, Object>(); For (Object k: json.keyset ()) {Object v = json.get(k); // If the inner layer is a JSON array, If (v instanceof JSONArray) {List<Map<String, Object>> List = new ArrayList<Map<String, Object>>(); Iterator<JSONObject> it = ((JSONArray) v).iterator(); while (it.hasNext()) { JSONObject json2 = it.next(); list.add(parseJSON2Map(json2)); } map.put(k.toString(), list); } else if (v instanceof JSONObject) {// If (v instanceof JSONObject) {map.put(k.tostring (), parseJSON2Map((JSONObject) v)); Map.put (k.tostring (), v);} else {// If the inner layer is a normal object, put directly into the map. } } return map; } @param jsonStr @return */ public static Map<String, Object> parseJSONstr2Map(String jsonStr) { JSONObject json = JSONObject.fromObject(jsonStr); Map<String, Object> map = parseJSON2Map(json); return map; }}Copy the code

3. Using API interface calls, the essential is of course the application of JSON string. This requires a reference to an external JAR package, either ali’s FastJson or the usual jSON-lib you’re familiar with. Or take a look at a simple use of JSON in this article. Blog.csdn.net/qq_41334351…

Original link: blog.csdn.net/qq_41334351…