An api interface invocation example using Java to implement a national weather forecast

  • 2020-05-10 18:14:17
  • OfStack

step1: select this sample interface is "the national weather forecast interface" aggregated data url: http: / / www juhe. cn docs/api/id / 39 / aid / 87

step2: each interface needs to pass in 1 parameter key, which is equivalent to the user's token, so step 1 you need to apply for 1 key.

step3: studied java classmates know, when we don't understand the intent of a class or method and thought, we can go to check the document, there is no exception, and for English is not very good classmates very fortunately, aggregation documents are Chinese version of the website, rather than reading java source document in English should be a lot easier. The national weather forecast interface below six subinterface, opened the first interface link, see document found need into a city name or city ID parameter, the parameter we can use is the interface to get 6 (pick up The call interface is involved in requesting network resources, and here I have encapsulated a utility class that contains two methods, GET and POST.

step4: the code is as follows:

Demo1: network access utility class (encapsulates 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.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
 *  Network access utility class 
 * @author silk
 *
 */
public class PureNetUtil {
 /**
  * get Method direct call post methods 
  * @param url  The network address 
  * @return  Return network data 
  */
 public static String get(String url){
  return post(url,null);
 }
 /**
  *  set post Methods to obtain network resources , If the parameter is null, It's actually set to get methods 
  * @param url  The network address 
  * @param param  Request parameter key-value pairs 
  * @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.*/
    // The default is false,post Methods need to write arguments , set true
    conn.setDoOutput(true);
    // set post methods , The default get
    conn.setRequestMethod("POST");
    // Get the output stream 
    OutputStream out=conn.getOutputStream();
    // The output stream is encapsulated into a high-level output stream 
    BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));
    // Encapsulates parameters in the form of key-value pairs 
    for(Map.Entry s:param.entrySet()){
     sb.append(s.getKey()).append("=").append(s.getValue()).append("&");
    }
    // Writes the parameters through the output stream 
    writer.write(sb.deleteCharAt(sb.toString().length()-1).toString());
    writer.close();//1 Need to shut down , Otherwise, an error may occur with incomplete parameters 
    sb=null;
   }
   conn.connect();// Establish a connection 
   sb=new StringBuffer();
   // Gets 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 sample city list interface


package juheAPI;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 *  Get the list of cities 
 *  National weather forecast interface call JAVA The sample 
 *  dtype  string N  Return data format: json or xml, The default json 
 *  key  string  Y  You apply for key 
 * @author silk
 *
 */
public class GetCityList {
 /**
  *  Call get 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 1 An encapsulated get and post Method to get the utility class for network request data 
  return PureNetUtil.get(url);// use get methods 
 }
 /**
  *  After calling the interface to return the data , Analytical data , According to the input city name corresponding ID
  * @param cityName  The city name 
  * @return  Return the corresponding ID
  */
 public static String getIDBycityName(String cityName) {
  String result=excute();// Return interface results , get 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 Represents a successful return of data 
    result=obj.getString("result");// Get the list of cities json Format string array 
    JSONArray arr=JSONArray.fromObject(result);
    for(Object o:arr){// right arr To traverse the 
     // Put in the array 1 a json Number of strings to parse 
     obj=JSONObject.fromObject(o.toString());
     /* At this time obj Such as  {"id":"2","province":" Beijing ","city":" Beijing ","district":" haidian "}*/
     // In order to city this key The record that needs to be sought for clues 
     result=obj.getString("district");
     // Prevent the input city name is not complete , Such as suzhou import for suzhou , Similar to fuzzy queries 
     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: the call queries the weather by city name /id


package juheAPI;
 
import net.sf.json.JSONObject; 
/**
 *  By city name /id Query the weather 
 * @author silk
 *
 */
public class WeatherReportByCity {
 /**
  *  Get by city name 
  * @param cityName
  * @return
  */
 public static String excute(String cityName){
  String url=// Here to return json Sample format data , so format=2, Take, for example, the city name ,cityName Introduced into Chinese 
    "http://v.juhe.cn/weather/index?cityname="+cityName+"&key=***a7558b2e0bedaa19673f74a6809ce";
  return PureNetUtil.get(url);// Get the returned data through the utility class 
 }
 /**
  *  Gets the value in the returned data 1 Two attribute examples , Take today's temperature as an example 
  * "temperature": "8 ℃ ~20 ℃ "   The temperature today 
  * @param args
  * @return 
  */
 public static String GetTodayTemperatureByCity(String city) {
  String result=excute(city);
  if(result!=null){
   JSONObject obj=JSONObject.fromObject(result);
   /* Gets the return status code */
   result=obj.getString("resultcode");
   /* If the status code is 200 Indicates that the returned data was successful */
   if(result!=null&&result.equals("200")){
    result=obj.getString("result");
    // At this time result There are more than one key, Can the key To traverse the , I get the properties 
    obj=JSONObject.fromObject(result);
    // The corresponding temperature today key is today
    result=obj.getString("today");
    obj=JSONObject.fromObject(result);
    // The temperature today is correct key 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 the weather type and presentation list interface


package juheAPI;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 *  The weather type and identification list interface is called JAVA The sample 
 * @author silk
 */
public class GetWeatherSignAndTypeList {
 // Address of the interface , Because you just need to pass it in 1 fixed key For the parameter , So let's make that constant 
 private static final String URL= "http://v.juhe.cn/weather/uni?key=***a7558b2e0bedaa19673f74a6809ce";
 /**
  *  Get the data through the utility class 
  * @return
  */
 public static String excute(){
  return PureNetUtil.get(URL);// Call the utility class to get the interface data 
 }
 /**
  *  Get by traversing groups 
  * @param wid The corresponding weather id
  * @return  Name of the weather 
  */
 public static String getWeatherByWid(String wid) {
  String result=excute();// Get interface data 
  if(result!=null){
   JSONObject obj=JSONObject.fromObject(result);
   result=obj.getString("resultcode");
   /* Gets the 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){// Through the array 
     obj=JSONObject.fromObject(o.toString());
     // If you traverse the required data and return the result directly , According to the key(wid) get value To determine whether it is equal to the incoming 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, refer to the documentation carefully, that is, return step3: see the documentation!


Related articles: