Example of API interface invocation for National weather forecast with Java _java

Source: Internet
Author: User
Tags key string recode stringbuffer

Step1: Select the interface "National Weather forecast Interface" aggregated data url:http://www.juhe.cn/docs/api/id/39/aid/87 The example in this article

Step2: Each interface needs to pass in a parameter key, which is equivalent to the user's token, so the first step is to apply for a key.

step3: The students who have studied Java know that when we do not understand a class or method of their intentions and ideas, we can go to see the document, here is no exception, and for English is not particularly good for the students are very fortunate that the aggregation site documents are in the Chinese version, It's much easier than reading English documents in Java source code. National Weather forecast interface There are six sub interfaces, open the first interface link, see the document found that need to pass a city name or city ID parameters, this parameter we can get through the sixth sub-interface ( The invocation of parameters between interfaces is similar to a call between methods in Java, that is, to support city list fetching. In the example we call this interface first. The calling interface involves asking for network resources, and here I encapsulate a tool class that contains two methods of Get and post.

STEP4: The code is as follows:

DEMO1: Network Access Tool class (encapsulating 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 Tool class * @author SILK * * * * * * * * * * * */public class Purenetutil {/** * Get method directly call post method * @param URL network address * @return
 Returns network data */public static String get (string url) {return post (url,null); /** * Set POST method to obtain network resources, if the parameter is null, actually set to get method * @param URL network address * @param param request Parameter key value pairs * @return return READ Data * * * Publ
  IC 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 is used for input and/or output. Set the dooutput * flag to TRUE if you are intend to the URL connection for output, * fAlse if not.
    The default is false.*////defaults to False,post method requires write parameters, set true Conn.setdooutput (true);
    Set the Post method, the default get Conn.setrequestmethod ("post");
    Obtain output stream OutputStream out=conn.getoutputstream ();
    The output stream is encapsulated into the advanced output stream BufferedWriter writer=new bufferedwriter (New OutputStreamWriter (out)); Encapsulates the parameter as a key-value pair in the form for (Map.entry S:param.entryset ()) {Sb.append (S.getkey ()). Append ("="). Append (S.getvalue ()). Append ("
    & ");
    ///writes the parameter to Writer.write (Sb.deletecharat (sb.tostring (). Length ()-1) with the output stream. toString ());
   Writer.close ()//must be closed, otherwise there may be error sb=null parameter;
   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 so reads from this open connection//Get input stream from connection InputStream In=con
    N.getinputstream ();
    Encapsulates the input stream reader=new BufferedReader (new InputStreamReader (in));
    String Str=null;
    Sb=new StringBuffer (); //read data from 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 connection conn.disconnect ();
 return null; }
 
}

Demo2: Call Get City List interface Example

Package Juheapi;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
 /** * Get City List * National Weather forecast Interface Call Java example * Dtype string N return Data format: JSON or XML, default JSON * key string Y you requested key * @author Silk */public class Getcitylist {/** * call gets the city list interface, returns all data * @return return interface data/public static String Excute () {STR ing url= "http://v.juhe.cn/weather/citys?key=***a7558b2e0bedaa19673f74a6809ce";//interface URL//
  Purenetutil is a tool class return Purenetutil.get (URL) that encapsulates the get and post methods to obtain network request data,//Use Get method}/** * Call interface returns data, parses the data, gets the corresponding ID according to the input city name * @param cityname City name * @return return the corresponding ID */public static string Getidbycityname (String cityname) {string result=e
   Xcute (); Returns the interface result, obtains the JSON format data if (result!=null) {Jsonobject obj=jsonobject.fromobject (results); Result=obj.getstring ("ResultCode");/Get Return Status code if (Result!=null&&result.equals ("200")) {//200 indicates successful return of data result
    =obj.getstring ("result");//Get the city list of the JSON-formatted string array Jsonarray arr=jsonarray.fromobject. for (Object O:arr) {//ARRTraversal//Parse a JSON number string in an array obj=jsonobject.fromobject (o.tostring ()); /* At this time obj such as {"id": "2", "Province": "Beijing", "City": "Beijing", "District": "Haidian"}*///to city this key for clues to determine the need to find this record Result=obj.getstri
     Ng ("District"); Prevent input of city names, such as Suzhou input for 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/ID query weather based on city name

Package Juheapi; 
Import Net.sf.json.JSONObject; /** * According to the city name/ID inquiry Weather * @author Silk * */public class Weatherreportbycity {/** * According to the city name get * @param cityname * @re
    Turn/public static string Excute (String cityname) {string url=//here to return an example of JSON format data, so format=2 to take the city name for example, CityName incoming Chinese
  "Http://v.juhe.cn/weather/index?cityname=" +cityname+ "&key=***a7558b2e0bedaa19673f74a6809ce"; return Purenetutil.get (URL); Get returned data through the tool class}/** * Get a sample of attributes from the return data, here for an example of today's temperature * "Temperature": "8℃~20℃" Today temperature * @pa
  Ram 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 indicating the return data success/if (Result!=null&&result.equals (")") {result=obj.getstring ("result");
    At this point, the data in result has multiple keys, and the key can be traversed to obtain the obj=jsonobject.fromobject of attributes. Today's temperature corresponds to the key is todays result=obj.getsTring ("Today");
    Obj=jsonobject.fromobject (result);
    Today's temperature should be key is temperature result=obj.getstring ("Temperature");
   return result;
 } return result;
 public static void Main (string[] args) {System.out.println (gettodaytemperaturebycity ("Suzhou")); }
}

Demo4: Call weather type and representation List interface Example

Package Juheapi;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
 /** * Weather type and Identity list interface Invoke Java example * @author silk/public class Getweathersignandtypelist {//interface address, because only need to pass a fixed key as parameter, so set as constant
 private static final String url= "Http://v.juhe.cn/weather/uni?key=***a7558b2e0bedaa19673f74a6809ce";  /** * Get data through tool class * @return/public static String Excute () {return purenetutil.get (URL);//Call tool class get interface data}/** * Use traversal array to get * @param wid weather corresponding ID * @return Weather name/public static string Getweatherbywid (String wid) {string Resul
   T=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) {//traversal array obj=jsonobject.fromobject (o.tostring ()); If you traverse to the desired data and return the result directly, the value judged by key (WID) 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: Call interface If the status code is not 200, carefully refer to the document description, that is, return Step3: Look at the document!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.