The following example code applies to the API at www.apishop.net. Before invoking the code example using the interface mentioned in this article, you need to apply for the corresponding API service.

  1. Driving test question bank: Get driving test questions and answers
  2. ISBN Query: Queries the ISBN information using the 10-digit or 13-digit ISBN, including the name of the book, author, publisher, price, publication date, print number, binding method, language, and abstract.
  3. Calendar query: query the specified date of the week, constellation, lunar, zodiac, heaven and earth branches, year of the year, the almanac related blessing god, Happy God, appropriate avoid and other information, also can carry out the lunar calendar conversion.
  4. Holiday query: annual holiday query
  5. Idioms: including pronunciation, interpretation, from allusion, synonyms, antonyms, examples and other data, can carry out idiom solitaryong, idiom guessing game development.
  6. Riddles: puzzles, animals, lantern riddles, objects, children, plants, idioms and other types of riddles.
  7. Standard Chinese code query: conversion between Chinese and code
  8. Xinhua Dictionary: contains Chinese pronunciation, radical, structure, stroke sequence, wubi, English, explanation, content, polyphonic characters, etc.
  9. Chinese dictionary: including the pronunciation, interpretation, examples, origin, synonyms, antonyms and other data, including idioms, proverbs, etc.
  10. Aphorism: covering life, inspirational and other aspects
  11. Inspire yourself, understand life, classic quotes
  12. Tongue twisters: popular tongue twisters, classic tongue twisters, tongue twisters

API Shop (apishop.net) to provide as many as 50 common third-party API, you can download the code from the lot sample collection: https://github.com/apishop/All-APIs

The above interfaces all contain code examples for PHP, Python, C#, and Java. Take the API for obtaining the tongue twister list as an example:

(1) Based on PHP get password list API service request code example

<? php$method = "POST";
$url = "https://api.apishop.net/common/tongue/getTongueList";
$headers = NULL;
$params = array(
    "page"= >"", / / the page number"pageSize"= >"", // Get the number of entries (maximum 15, default 10));$result = apishop_curl($method.$url.$headers.$params);
If ($result) {
    $body = json_decode($result["body"], TRUE);
    $status_code = $body["statusCode"];
    If ($status_code= ="000000") {// If the status code is 000000, the request is successfulecho "Request successful:" . $result["body"];
    } else{// If the status code is not 000000, the request failsecho "Request failed:" . $result["body"]; }}else{// The returned content is abnormal, and the request fails to be sent. The following parameters can be modified according to the service logicecho "Sending request failed"; } /** * forward the request to the destination host * @param$methodString request method * @param$URLString Request address * @param null$headersRequest header * @param NULL$paramRequest parameter * @return array|bool
 */
function apishop_curl(&$method, &$URL, &$headers = NULL, &$param= NULL) {// Initialize the request$require = curl_init($URL); // Check whether HTTPS is available$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) {// Skip certificate check curl_setopt($require, CURLOPT_SSL_VERIFYPEER, FALSE); // Check whether the domain name curl_setopt($require, CURLOPT_SSL_VERIFYHOST, 2);
    }
    if ($headers) {// Set the request header curl_setopt($require, CURLOPT_HTTPHEADER, $headers); } // curl_setopt($require, CURLOPT_RETURNTRANSFER, TRUE); // redirect curl_setopt($require, CURLOPT_FOLLOWLOCATION, TRUE); Curl_setopt (curl_setopt($require, CURLOPT_HEADER, TRUE); // Send the request$response = curl_exec($require); // Get the header length$headerSize = curl_getinfo($require, CURLINFO_HEADER_SIZE); // Close the request curl_close($require);
    if ($response) {// Returns the header string$header = substr($response, 0, $headerSize); / / return to the 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]); // Convert the return result header into an array$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"= >$body
        );
    } else {
        returnFALSE; }}Copy the code

(2) Python based access to the list of password API service request code example

#! /usr/bin/env python
# -*- coding: utf-8 -*-
Test environment: PYTHon2.7
# install requests dependencies => PIP install requests/ easy_install requests

Import the Requests dependency
import requests
import json
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

def apishop_send_request(method, url, params=None, headers=None):
    ' '@param method STR Request method @param URL STR request address @param params dict Request parameter @param headers dict Request header '' '
    method = str.upper(method)
    if method == 'POST':
        return requests.post(url=url, data=params, headers=headers)
    elif method == 'GET':
        return requests.get(url=url, params=params, headers=headers)
    else:
        return None

method = "POST"
url = "https://api.apishop.net/common/tongue/getTongueList"
headers = None
params = {			
    "page":"".# page
    "pageSize":"".# get the number of entries (Max. 15, default 10)
}
result = apishop_send_request(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') :If the status code is 000000, the request is successful
        print('Request successful: %s' % (body,))
    else:
        # If the status code is not 000000, the request fails
        print('Request failed: %s' % (body,))
else:
    Failed to send the request
    print('Send request failed')
Copy the code

(3) C# based get password list API service request code example

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 {/** * Forwards requests to the destination host * @param method String Request 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, Dictionary<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 itemin 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 (StreamWriter swrite = new StreamWriter(requestStream))
						{
							swrite.Write(paramData);
						}
					}
				}

				HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
				using (Stream responseStream = wbResponse.GetResponseStream())
				{
					using (StreamReader sread = 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".""); Dictionary<string, string> headers = null; string result = apishop_send_request(method, url, param, headers);if (result == "") {// Return content is abnormal, send request failed Console.WriteLine("Sending request failed");
				return;
			}

			Response res = new JavaScriptSerializer().Deserialize<Response>(result);
			if (res.statusCode == "000000") {// If the status code is 000000, the request is successful Console."Request successful: {0}", result));
			}
			else{// If the status code is not 000000, the request fails Console.WriteLine(string.Format("Request failed: {0}", result)); } Console.ReadLine(); }}}Copy the code

(4) Based on Java to get the password list 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 public class Api {/** * * param url interface address * param requestMethod requestMethod * param params transmits parameters. Important: parameter values must be transcoded in Base64 *returnPublic static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params){ InputStream is = null; try{ String parameters ="";
			boolean hasParams = false; // Concatenate the set of parameters into a specific format, for example, name=zhangsan&age=24for (String key : params.keySet()){
				String value = URLEncoder.encode(params.get(key), "UTF-8");
				parameters += key + "=" + value + "&";
				hasParams = true;
			}
			if(hasParams){ parameters = parameters.substring(0, parameters.length() - 1); } // whether the request mode isGet Boolean isGet ="get".equalsIgnoreCase(requestMethod); // whether the request mode isPost Boolean isPost ="post".equalsIgnoreCase(requestMethod);
			if (isGet){
				url += "?"+ parameters; } URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); // Request parameter Type (when using restlet framework, content-Type must be set to "" empty for compatibility with framework) conn.setrequestProperty ("Content-Type"."application/octet-stream");
			//conn.setRequestProperty("Content-Type"."application/x-www-form-urlencoded"); // Set connection timeout conn.setConnectTimeout(50000); Conn. setReadTimeout(50000); // Set to output to the HttpURLConnection object. Since post puts request parameters in the HTTP body, it needs to be set to true, defaultfalse
			if (isPost){
				conn.setDoOutput(true); } // Set the read from the HttpURLConnection object. The default istrue
			conn.setDoInput(true); // Set whether to use cache. Post mode does not use cacheif (isPost){
				conn.setUseCaches(false); } // set the requestMethod. The default is GET conn.setrequestmethod (requestMethod); // Post requires passing the argument to the conn objectif(isPost){ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(parameters); dos.flush(); dos.close(); Is = conn.getinputStream ();} // Read the response message from the HttpURLConnection object. }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".""); 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"){// If the status code is 000000, the request is successful system.out.println ("Request successful:" + jsonObject.getString("result"));
		    }else{// If the status code is not 000000, the request failed system.out.println ("Request failed:" + jsonObject.getString("desc")); }}elseSystem.out.println() {// The returned content is abnormal, and the request fails to be sent. The following can be modified according to the service logic."Sending request failed"); }}}Copy the code