Code sample collection of knowledge Class API calls: Driving test Questions Library, ISBN number query, perpetual calendar query, etc.

Source: Internet
Author: User

The following sample code applies to the API under the Www.apishop.net Web site, and you need to request the appropriate API service before invoking the code sample using the interface mentioned in this article.

    1. Driving Test Questions Library: Get driving questions and answers
    2. ISBN ISBN query: through 10-bit or 13-bit ISBN query ISBN information, including the title, author, publishing house, Price, publication date, impressions, binding method, language, abstract and other information.
    3. Perpetual Calendar Query: Query the date of the week, constellation, Lunar, Zodiac, Zodiac, age, almanac related to the blessing of God, Rican spirit, Yi Bogey and other information, you can also lunisolar conversion.
    4. Holiday query: Year-round holiday inquiry
    5. Idiom Daquan: Including pronunciation, interpretation, from the allusions, synonyms, antonyms, examples and other data, can be used in idioms solitaire, idiom guessing game development.
    6. Riddles: puzzles, animals, lantern riddles, objects, children, plants, and idioms, and various types of riddles.
    7. Standard Chinese code query: Chinese, code to convert each other
    8. Xinhua Dictionary: Contains the pronunciation of Chinese characters, radicals, structure, stroke order, Wubi, English, Interpretation, content, Polyphone and so on.
    9. Chinese dictionary: Including the pronunciation of words, explanations, examples, from, synonyms, antonyms and other data, including idioms, sayings and so on.
    10. Famous aphorism: Covering Life, inspirational and many other aspects
    11. Inspiring yourself, understanding life, classic Sayings
    12. Tongue twisters: Popular tongue twisters, classic tongue twisters, tongue twisters Daquan

**api Shop (apishop.net) offers up to 50 common third-party APIs that can be downloaded from GitHub on a collection of code samples: https://github.com/apishop/all-apis**

The above interface contains code examples in four languages, such as PHP, Python, C #, and Java , to get the list of Tongue Twisters API as an example:

(1) PHP-based code example for getting a list of Tongue Twisters API service requests

<?php$method = "POST"; $url = "Https://api.apishop.net/common/tongue/getTongueList"; $headers = NULL; $params = Array ( "Page" = "" ",//page number" PageSize "" ",//Get the number of bars (up to 15, default)); $result = Apishop_curl ($method, $url, $headers, $pa    Rams); If ($result) {$body = Json_decode ($result ["Body"], TRUE);    $status _code = $body ["StatusCode"];    If ($status _code = = "000000") {//Status code is 000000, the request succeeds Echo "request succeeded:". $result ["Body"];    } else {//Status code not 000000, indicating that the request failed echo "request failed:". $result ["Body"]; }} else {//return content exception, send request failed, the following can modify echo "send request failed" according to business logic;} /** * Forward request to destination host * @param $method string Request method * @param $URL string Request address * @param NULL $headers request header * @param null $param request parameter Number * @return Array|bool */function apishop_curl (& $method, & $URL, & $headers = null, & $param = null) {///Initial    The initiation Request $require = Curl_init ($URL); Determine if HTTPS $isHttps = substr ($URL, 0, 8) = = "https://"?    True:false; Set Request mode switch ($method) {case "Get": curl_setopt ($require, Curlopt_customrequest, "get");        Break            Case "POST": curl_setopt ($require, Curlopt_customrequest, "post");        Break    Default:return FALSE;    } if ($param) {curl_setopt ($require, Curlopt_postfields, $param);        } if ($isHttps) {//skips the certificate check curl_setopt ($require, Curlopt_ssl_verifypeer, FALSE);    Check the certificate for setting the domain name curl_setopt ($require, Curlopt_ssl_verifyhost, 2);    } if ($headers) {//Set request Header curl_setopt ($require, Curlopt_httpheader, $headers);    }//Return results are not directly output curl_setopt ($require, Curlopt_returntransfer, TRUE);    REDIRECT Curl_setopt ($require, curlopt_followlocation, TRUE);    The return header contains the re-output in curl_setopt ($require, Curlopt_header, TRUE);    Send Request $response = curl_exec ($require);    length $headerSize = Curl_getinfo ($require, curlinfo_header_size);    Close Request Curl_close ($require); if ($response) {//Return header string       $header = substr ($response, 0, $headerSize);        return body $body = substr ($response, $headerSize);        Filter hidden illegal characters $bodyTemp = json_encode (Array (0 = $body));        $bodyTemp = Str_replace ("\ufeff", "", $bodyTemp);        $bodyTemp = Json_decode ($bodyTemp, TRUE);        $body = Trim ($bodyTemp [0]);        Returns the result head to a group $respondHeaders = array ();        $header _rows = Array_filter (Explode (Php_eol, $header), "trim");            foreach ($header _rows as $row) {$keylen = Strpos ($row, ":");                    if ($keylen) {$respondHeaders [] = Array ("Key" = substr ($row, 0, $keylen),            "Value" = Trim (substr ($row, $keylen + 1)));    }} return Array ("headers" = $respondHeaders, "Body" and "$body");    } else {return FALSE; }}

(2) Python-based code example to get a list of Tongue Twisters API service requests

#!/usr/bin/env python#-*-coding:utf-8-*-# test Environment: python2.7# Install requests dependent = Pip Install Requests/easy_install reque sts# Import requests Dependent import Requestsimport Jsonimport sysreload (SYS) sys.setdefaultencoding (' Utf-8 ') def apishop_send_ Request (method, URL, Params=none, headers=none): "' Forward request to destination host @param method str request Methods @param URL Str requested address @ param params dict request parameter @param headers Dict Request Header "method = Str.upper (method) If method = = ' POST ': Retu RN Requests.post (Url=url, Data=params, headers=headers) elif method = = ' GET ': Return requests.get (Url=url, param S=params, headers=headers) Else:return Nonemethod = "POST" url = "Https://api.apishop.net/common/tongue/getTongu EList "headers = Noneparams = {" page ":", #页码 "pageSize": ", #获取条数 (up to 15, default)}result = Apishop_send_reque    St (Method=method, Url=url, Params=params, headers=headers) If result:body = result.text response = json.loads (body) Status_code = response["statuscOde "] if (Status_code = = ' 000000 '): # status code is 000000, indicating the request succeeded print (' request succeeded:%s '% (body)) ' Else: # status Code Not 000000, description request failed print (' request failed:%s '% (body)) Else: # Return content exception, send request failed print (' Send request failed ')

(3) C #-based code example for getting a list of Tongue Twisters API service requests

Using system;using system.collections.generic;using system.io;using system.net;using System.Text;using System.web.script.serialization;namespace Apishop_sdk{class program{/** * Forward request to destination Host * @param method string Requester Method * @param URL string request address * @param params dictionary<string,string> request parameter * @param headers dictionary&lt ;string,string> Request Header * @return string **/static string Apishop_send_request (String method, string URL, Dictio nary<string, string> param, dictionary<string, string> headers) {string result = string.        Empty;                try {string paramdata = ""; if (param! = null && param.                    Count > 0) {StringBuilder sbuilder = new StringBuilder (); foreach (var item in param) {if (Sbuilder. Length > 0) {sbuilder.         Append ("&");               } sbuilder. Append (item. Key + "=" + Item.                    Value); } Paramdata = Sbuilder.                ToString (); } method = method.                ToUpper (); if (method = = "GET") {URL = string. Format ("{0}?{                1} ", URL, paramdata);                } HttpWebRequest wbrequest = (HttpWebRequest) webrequest.create (URL);                if (method = = "Get") {Wbrequest.method = "get";                    } else if (method = = "Post") {Wbrequest.method = "post";                    Wbrequest.contenttype = "application/x-www-form-urlencoded";                    Wbrequest.contentlength = Encoding.UTF8.GetByteCount (Paramdata); using (Stream Requeststream = Wbrequest.getrequeststream ()) {using (streamwrite R swrite = new StreamWriter (requeststrEAM) {Swrite.                        Write (Paramdata); }}} HttpWebResponse Wbresponse = (httpwebresponse) wbrequest.getresponse                (); using (Stream Responsestream = Wbresponse.getresponsestream ()) {using (StreamReader SRE AD = new StreamReader (responsestream)) {result = Sread.                    ReadToEnd ();            }}} catch {return "";        } return result;        } class Response {public string statusCode;            } static void Main (string[] args) {string method = "POST";            String url = "Https://api.apishop.net/common/tongue/getTongueList";                        dictionary<string, string> param = new dictionary<string, string> (); Param. ADD ("Page "," "); Page param. ADD ("PageSize", "");            Gets the number of bars (up to 15, default) dictionary<string, string> headers = null;            string result = Apishop_send_request (method, URL, param, headers);                if (result = = "") {//return content exception, send request failed Console.WriteLine ("Send request Failed");            Return } Response res = new JavaScriptSerializer ().            Deserialize<response> (result); if (Res.statuscode = = "000000") {//The status code is 000000, the request succeeds Console.WriteLine (STRING.F            Ormat ("request succeeded: {0}", result)); } else {//status code is not 000000, indicating that the request failed Console.WriteLine (string.            Format ("request failed: {0}", result));        } console.readline (); }    }}

(4) Java-based code example for getting a list of Tongue Twisters API service requests

Package Net.apishop.www.controller;import Java.io.dataoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Java.net.urlencoder;import Java.util.HashMap;import Java.util.map;import com.alibaba.fastjson.jsonobject;/*** httpurlconnection Access Remote interface tool */public class Api{/** * method Body Description: To The remote interface initiates the request and returns the byte stream type result * param URL interface address * param Requestmethod Request method * param params pass parameter focus: parameter values need to be transcoded with Base64 * r Eturn inputstream Return result */public static InputStream httprequesttostream (string url, string requestmethod, Map<str        ING, string> params) {InputStream is = null;            try{String parameters = "";            Boolean hasparams = false; Stitching a collection of parameters into a specific format, such as name=zhangsan&age=24 for (String Key:params.keySet ()) {String value = URL    Encoder.encode (Params.get (key), "UTF-8");            Parameters + = key + "=" + Value + "&";            Hasparams = true;            } if (hasparams) {parameters = parameters.substring (0, Parameters.length ()-1);            }//Whether the request method is get Boolean isget = "Get". Equalsignorecase (Requestmethod);            Whether the request mode is post Boolean isPost = "Post". Equalsignorecase (Requestmethod);            if (isget) {URL + = "?" + parameters;            } URL u = new url (URL);            HttpURLConnection conn = (httpurlconnection) u.openconnection (); The requested parameter type (when using the Restlet framework, the Content-type must be set to "empty" for the framework to be compatible) Conn.setrequestproperty ("Content-type", "Application/octet            -stream ");            Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");            Set the connection timeout time conn.setconnecttimeout (50000);            Set read return timeout time conn.setreadtimeout (50000); Sets the output to the HttpURLConnection object because the POSThe T method places the request parameter inside the HTTP body, so it needs to be set to Ture, and the default False if (IsPost) {conn.setdooutput (true);            }//Set read from HttpURLConnection object, default is True Conn.setdoinput (true);            Set whether to use cache, Post mode cannot use cache if (isPost) {conn.setusecaches (false);            }//Set the request mode by default to get Conn.setrequestmethod (Requestmethod); The Post method needs to output the passed parameters to the Conn object if (isPost) {DataOutputStream dos = new DataOutputStream (conn.getout                Putstream ());                Dos.writebytes (parameters);                Dos.flush ();            Dos.close ();        ///Read the response from the HttpURLConnection object//The request is only formally initiated when executing the statement is = Conn.getinputstream ();        }catch (unsupportedencodingexception e) {e.printstacktrace ();        }catch (malformedurlexception e) {e.printstacktrace ();        }catch (IOException e) {e.printstacktrace ();    } return is; }   public static void Main (string args[]) {string url = "Https://api.apishop.net/common/tongue/getTongueList";        String Requestmethod = "POST";                 map<string, string> params = new hashmap<string, string> (); Params.put ("page", ""); Page Params.put ("PageSize", "");        Gets the number of bars (up to 15, default) String result = null;            try{InputStream is = Httprequesttostream (URL, requestmethod, params);            Byte[] B = new byte[is.available ()];            Is.read (b);        result = new String (b);        }catch (IOException e) {e.printstacktrace ();            } if (Result! = null) {Jsonobject jsonobject = Jsonobject.parseobject (result);            String Status_code = jsonobject.getstring ("StatusCode"); if (Status_code = = "000000") {//The status code is 000000, the request succeeds System.out.println ("Request succeeded:" + jsonobject.            GetString ("result")); }else{//Status code not 000000, indicating request failed               SYSTEM.OUT.PRINTLN ("Request failed:" + jsonobject.getstring ("desc"));        }else{//Return content exception, send request failed, the following can be modified according to business logic self-System.out.println ("Send request Failed"); }    }}

Code sample collection for knowledge Class API calls: Drive question Library, ISBN number query, perpetual calendar query, etc.

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.