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.
- NBA matches: NBA Basketball Tournament schedule Related information
- TV shows: TV schedules for CCTV and local TV, including TV content for the week and next week
**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 station classification API as an example:
(1) Code example of PHP-based access to classification API service requests for stations
<?php$method = "POST"; $url = "Https://api.apishop.net/common/tv/queryCategory"; $headers = NULL; $params = Array ( $result = Apishop_curl ($method, $url, $headers, $params), 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) {//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) Python-based code example for obtaining a TV station classification API service request
#!/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/tv/queryCategor Y "headers = Noneparams = {}result = Apishop_send_request (Method=method, Url=url, Params=params, Headers=head ERS) If result:body = result.text response = json.loads (body) Status_code = response["StatusCode"] if (status_ Code = = ' 000000 '): # status Code is 000000, stating 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 # code example for obtaining a TV station classification API service request
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< ;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/tv/queryCategory"; dictionary<string, string> param = new dictionary<string, string> (); 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 obtaining a TV station classification API service request
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/tv/queryCategory"; String Requestmethod = "POST"; map<string, string> params = new hashmap<string, string> (); 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 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"); } }}
Video Entertainment API call code sample collection: NBA games, TV shows, etc.