Examples of code samples for common class API calls in life: Postcode query, today's top news query, area code 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. Postcode inquiry: Through the postcode inquires the place name, through the place name inquires the ZIP code
    2. Today's top news inquiries: To provide the latest and most timely news information, including headlines, news, finance, sports, entertainment, military, education, science and technology, NBA, stock, constellation, women, health, childcare and other channels, 20 minutes update; Due to the large amount of data, if the request time-out, please request more.
    3. Area code query: Area code query (search area code by place name, check place name by area code)
    4. Simplified and traditional conversion: simple and traditional conversion
    5. Jokes Daquan: The latest and most timely joke jokes
    6. Zhou Gong solution dream: Zhou Gong Solution Dream Encyclopedia, Zhou Gong Solution Dream Query, free Zhou Gong dream
    7. Coodination query: Coodination time, origin, customs and health
    8. Standard Weight calculator: BMI (Body Mass Index, BMI), calculates whether your body is standard by height and weight
    9. Express Logistics query: Automatic identification of courier companies, providing including Shentong, Shun Fung, Yuantong, Yun Tatsu, in-Pass, Huitong, EMS, Daily, Guo Tong, darbond, home emergency delivery, such as hundreds of express logistics company tracking interface
    10. Exchange rate Query: Provide exchange rate conversion, a single currency corresponding to the popular currency exchange rate, including RMB, USD, EUR, GBP and other more than 100 currencies real-time exchange rate query.

**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 interfaces contain code examples in four languages, such as PHP, Python, C #, and Java , to query the exchange rate API for a given currency, for example:

(1) PHP-based query for the specified currency exchange Rate API Service Request code example

<?php$method = "POST"; $url = "Https://api.apishop.net/common/exchange/getExchangeByCurrency"; $headers = null;$ params = Array ("Currency" = "" ","//currency (Get all currency type interface) "); $result = Apishop_curl ($method, $url, $headers, $params);    F ($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;        To set the 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) {//Returns the 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) A Python-based query for the specified currency's Exchange Rate API Service Request code example

#!/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/exchange/getExc Hangebycurrency "headers = Noneparams = {" Currency ":" ", #货币 (get all currency kind interfaces)}result = apishop_send_request (Meth Od=method, Url=url, Params=params, headers=headers) If result:body = result.text response = json.loads (body) stat  Us_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 Stating that the request failed print (' request failed:%s '% (body)) Else: # Return content exception, send request failed print (' Send request failed ')

(3) C # Query The code example for the exchange Rate API service request for the specified currency

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/exchange/getExchangeByCurrency";                        dictionary<string, string> param = new dictionary<string, string> (); PAram. ADD ("Currency", "");            Currency (get all currency kinds in the interface) 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 query for the specified currency's Exchange Rate API Service Request code example

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/exchange/getExchangeByCurre        Ncy ";        String Requestmethod = "POST";                 map<string, string> params = new hashmap<string, string> (); Params.put ("Currency", "" ");        Currency (gets all currency kinds in the interface) 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 that the 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 of common class API calls for life: Postcode query, today's top news query, area code 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.