step1: Select the interface "National Weather Forecast Interface" as shown in this article. Aggregate data url: http://www.juhe.cn/docs/api/id/39/aid/87
step2: Each interface needs to pass a parameter key, which is equivalent to the user's token, so the first step you need to apply for a key.
step3: Students who have studied java know that when we don’t understand the intention and ideas of a class or method, we can check the document, and this is no exception. Fortunately for students who are not particularly good in English, the documents on the aggregation website are all in Chinese version, which should be much easier than reading the English documents in the java source code. There are six sub-interfaces under the national weather forecast interface. Open the first interface link and look at the document and find that you need to pass a city name or city ID parameter. This parameter can be obtained through the sixth sub-interface (the calls between interfaces are similar to calls between methods in java), that is, the acquisition of city lists is supported. So in the example, we call this interface first. Calling the interface involves the issue of requesting network resources. Here I encapsulate a tool class, including two methods: GET and POST.
step4: The code is as follows:
Demo1: Network access tool class (encapsulate get and post methods)
package juheAPI;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.URL;import java.util.Map;/** * Network access tool class* @author silk * */public class PureNetUtil { /** * get method directly calls the post method* @param url Network address* @return Return network data*/ public static String get(String url){ return post(url,null); } /** * Set the post method to obtain network resources. If the parameter is null, it is actually set as the get method* @param url Network address* @param param Request parameter key-value pair* @return Return read data*/ public static String post(String url,Map param){ HttpURLConnection conn=null; try { URL u=new URL(url); conn=(HttpURLConnection) u.openConnection(); StringBuffer sb=null; if(param!=null){//If the request parameter is not empty sb=new StringBuffer(); /*A URL connection can be used for input and/or output. Set the DoOutput * flag to true if you intend to use the URL connection for output, * false if not. The default is false.*/ //Default is false. The post method needs to write parameters and set true conn.setDoOutput(true); //Set the post method, default get conn.setRequestMethod("POST"); //Get the output stream OutputStream out=conn.getOutputStream(); //Encapsulate the output stream into advanced output stream BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out)); //Encapsulate the parameters into key-value pairs for(Map.Entry s:param.entrySet()){ sb.append(s.getKey()).append("=").append(s.getValue()).append("&"); } //Write the parameters through the output stream to writer.write(sb.deleteCharAt(sb.toString().length()-1).toString()); writer.close();//It must be closed, otherwise there may be an error with incomplete parameters sb=null; } connect();//Make a connection sb=new StringBuffer(); //Get the connection status code int recode=conn.getResponseCode(); BufferedReader reader=null; if(recode==200){ //Returns an input stream that reads from this open connection //Get the input stream from the connection InputStream in=conn.getInputStream(); //Encapsulate the input stream reader=new BufferedReader(new InputStreamReader(in)); String str=null; sb=new StringBuffer(); //Read data from the input stream while((str=reader.readLine())!=null){ sb.append(str).append(System.getProperty("line.separator")); } //Close the input stream reader.close(); if (sb.toString().length() == 0) { return null; } return sb.toString().substring(0, sb.toString().length() - System.getProperty("line.separator").length()); } } catch (Exception e) { e.printStackTrace(); return null; } finally{ if(conn!=null)//Close the connection conn.disconnect(); } return null; } } Demo2: Call to get the city list interface example
package juheAPI;import net.sf.json.JSONArray;import net.sf.json.JSONObject;/** * Get the city list* Example of calling JAVA in the national weather forecast interface* dtype string N Return data format: json or xml, default json * key string Y The key you applied for * @author silk * */public class GetCityList { /** * Call to get the city list interface, return all data* @return Return interface data*/ public static String excute(){ String url="http://v.juhe.cn/weather/citys?key=***a7558b2e0bedaa19673f74a6809ce";//Interface URL //PureNetUtil is a tool class that encapsulates get and post methods to obtain network request data return PureNetUtil.get(url);//Use get method} /** * After calling the interface to return the data, parse the data and get the corresponding ID based on the input city name * @param cityName CityName City name * @return Return the corresponding ID */ public static String getIDBycityName(String cityName) { String result=excute();//Return the interface result and get the json format data if(result!=null){ JSONObject obj=JSONObject.fromObject(result); result=obj.getString("resultcode");//Get the return status code if(result!=null&&result.equals("200")){//200 indicates successful return of data result=obj.getString("result");//Get the json format string array of the city list JSONArray arr=JSONArray.fromObject(result); for(Object o:arr){//Transfer arr//Parse a json numeric string in the array obj=JSONObject.fromObject(o.toString()); /*At this time obj is {"id":"2","province":"Beijing","city":"Beijing","district":"Haidian"}*/ //The record that needs to be found for judgment based on the key city as a clue result=obj.getString("district"); //Prevent the incomplete name of the input city, such as Suzhou City input as Suzhou, similar to fuzzy query if(result.equals(cityName)||result.contains(cityName)){ result=obj.getString("id");//Get ID return result; } } } } return result; } public static void main(String[] args) { System.out.println(getIDBycityName("Hong Kong")); }} Demo3: Call to check the weather based on the city name/id
package juheAPI; import net.sf.json.JSONObject; /** * Query the weather by city name/id* @author silk * */public class WeatherReportByCity { /** * Get */param cityName * @return */ public static String excute(String cityName){ String url=//Here is a json format data example, so format=2. Taking the city name as an example, cityName is passed into the Chinese "http://v.juhe.cn/weather/index?cityname="+cityName+"&key=***a7558b2e0bedaa19673f74a6809ce"; return PureNetUtil.get(url);//Get return data through tool class} /** * Get an example of an attribute in the returned data, here is a sample of getting today's temperature* "temperature": "8℃~20℃" Today's temperature* @param args * @return */ public static String GetTodayTemperatureByCity(String city) { String result=excute(city); if(result!=null){ JSONObject obj=JSONObject.fromObject(result); /*Get return status code*/ result=obj.getString("resultcode"); /*If the status code is 200, it means that the data is returned successfully*/ if(result!=null&&result.equals("200")){ result=obj.getString("result"); //At this time, there are multiple keys in the data in the result, and the key can be traversed to obtain the attribute obj=JSONObject.fromObject(result); //The key corresponding to today's temperature is today result=obj.getString("today"); obj=JSONObject.fromObject(result); //The corresponding key of today's temperature is temperature result=obj.getString("temperature"); return result; } } return result; } public static void main(String[] args) { System.out.println(GetTodayTemperatureByCity("Suzhou")); }} Demo4: Example of calling weather type and representation list interface
package juheAPI;import net.sf.json.JSONArray;import net.sf.json.JSONObject;/** * Example of calling JAVA for weather type and identification list interface* @author silk */public class GetWeatherSignAndTypeList { //Interface address, because only a fixed key needs to be passed as a parameter, it is set to a constant private static final String URL= "http://v.juhe.cn/weather/uni?key=***a7558b2e0bedaa19673f74a6809ce"; /** * Get data through tool class* @return */ public static String exhaust(){ return PureNetUtil.get(URL);//Calling the tool class to get interface data} /** * Get * @param wid weather corresponding id * @return Weather name*/ public static String getWeatherByWid(String wid) { String result=excute();//Get interface data if(result!=null){ JSONObject obj=JSONObject.fromObject(result); result=obj.getString("resultcode"); /*Get return status code*/ if(result!=null&&result.equals("200")){ /*Get array data*/ result=obj.getString("result"); JSONArray arr=JSONArray.fromObject(result); for(Object o:arr){//Tranquility array obj=JSONObject.fromObject(o.toString()); //If you traverse the required data and return the result directly, obtain the value based on the key(wid) to determine whether it is equal to the passed parameter if(obj.getString("wid").equals(wid)){ result=obj.getString("weather"); return result; } } } } return result; } public static void main(String[] args) { System.out.println(getWeatherByWid("10")); }}step5: If the status code is not 200 when calling the interface, please refer carefully to the document instructions, which means returning to step3: Read the document!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.