知識類API調用的代碼示例合集:駕考題庫、ISBN書號查詢、萬年歷查詢等
阿新 • • 發佈:2018-03-04
system 之間 HP sts efault text set verify base
以下示例代碼適用於 www.apishop.net 網站下的API,使用本文提及的接口調用代碼示例前,您需要先申請相應的API服務。
- 駕考題庫:獲取駕考題目與答案
- ISBN書號查詢:通過10位或13位ISBN查詢書號信息,包含書名、作者、出版社、價格、出版日期、印次、裝幀方式、語種、摘要等信息。
- 萬年歷查詢:查詢指定日期的星期、星座、農歷、生肖、天幹地支、歲次、黃歷相關的福神、喜神、宜忌等信息,還可以進行陰陽歷轉換。
- 節假日查詢:全年節假日查詢
- 成語大全:包含發音、解釋、出自典故、近義詞、反義詞、例句等數據,可進行成語接龍、成語競猜等遊戲開發。
- 謎語大全:字謎、動物、燈謎、物品、兒童、植物、及成語等各種類型的謎語。
- 標準中文電碼查詢:中文、電碼之間相互轉換
- 新華字典:包含漢字的發音、部首、結構、筆順、五筆、英文、解釋、內容、多音字等。
- 漢語詞典:包括詞語的發音、解釋、例子、出自、近義詞、反義詞等數據,包含成語、俗語等。
- 名言警句:涵蓋人生、勵誌等多個方面
- 英語名言:激勵自己、領悟人生、經典名言
- 繞口令:熱門繞口令,經典繞口令,繞口令大全
**API Shop(apishop.net)提供多達50款的常用第三方API,可以從github上下載代碼示例合集:https://github.com/apishop/All-APIs**
以上接口均包含PHP、Python、C#和Java等四種語言的代碼示例,以 獲取繞口令列表 API為例:
(1)基於PHP的 獲取繞口令列表 API服務請求的代碼示例
<?php $method = "POST"; $url = "https://api.apishop.net/common/tongue/getTongueList"; $headers = NULL; $params = array( "page" => "", //頁碼 "pageSize" => "", //獲取條數(最多15條,默認10) ); $result = apishop_curl($method, $url, $headers, $params); If ($result) { $body = json_decode($result["body"], TRUE); $status_code = $body["statusCode"]; If ($status_code == "000000") { //狀態碼為000000, 說明請求成功 echo "請求成功:" . $result["body"]; } else { //狀態碼非000000, 說明請求失敗 echo "請求失敗:" . $result["body"]; } } else { //返回內容異常,發送請求失敗,以下可根據業務邏輯自行修改 echo "發送請求失敗"; } /** * 轉發請求到目的主機 * @param $method string 請求方法 * @param $URL string 請求地址 * @param null $headers 請求頭 * @param null $param 請求參數 * @return array|bool */ function apishop_curl(&$method, &$URL, &$headers = NULL, &$param = NULL) { // 初始化請求 $require = curl_init($URL); // 判斷是否HTTPS $isHttps = substr($URL, 0, 8) == "https://" ? TRUE : FALSE; // 設置請求方式 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) { // 跳過證書檢查 curl_setopt($require, CURLOPT_SSL_VERIFYPEER, FALSE); // 檢查證書中是否設置域名 curl_setopt($require, CURLOPT_SSL_VERIFYHOST, 2); } if ($headers) { // 設置請求頭 curl_setopt($require, CURLOPT_HTTPHEADER, $headers); } // 返回結果不直接輸出 curl_setopt($require, CURLOPT_RETURNTRANSFER, TRUE); // 重定向 curl_setopt($require, CURLOPT_FOLLOWLOCATION, TRUE); // 把返回頭包含再輸出中 curl_setopt($require, CURLOPT_HEADER, TRUE); // 發送請求 $response = curl_exec($require); // 獲取頭部長度 $headerSize = curl_getinfo($require, CURLINFO_HEADER_SIZE); // 關閉請求 curl_close($require); if ($response) { // 返回頭部字符串 $header = substr($response, 0, $headerSize); // 返回體 $body = substr($response, $headerSize); // 過濾隱藏非法字符 $bodyTemp = json_encode(array( 0 => $body )); $bodyTemp = str_replace("\ufeff", "", $bodyTemp); $bodyTemp = json_decode($bodyTemp, TRUE); $body = trim($bodyTemp[0]); // 將返回結果頭部轉成數組 $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 { return FALSE; } }
(2)基於Python的 獲取繞口令列表 API服務請求的代碼示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 測試環境: python2.7
# 安裝requests依賴 => pip install requests/ easy_install requests
# 導入requests依賴
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 請求方法
@param url str 請求地址
@param params dict 請求參數
@param headers dict 請求頭
‘‘‘
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":"", #頁碼
"pageSize":"", #獲取條數(最多15條,默認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‘):
# 狀態碼為000000, 說明請求成功
print(‘請求成功:%s‘ % (body,))
else:
# 狀態碼非000000, 說明請求失敗
print(‘請求失敗: %s‘ % (body,))
else:
# 返回內容異常,發送請求失敗
print(‘發送請求失敗‘)
(3)基於C#的 獲取繞口令列表 API服務請求的代碼示例
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
{
/**
* 轉發請求到目的主機
* @param method string 請求方法
* @param url string 請求地址
* @param params Dictionary<string,string> 請求參數
* @param headers Dictionary<string,string> 請求頭
* @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 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 (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", ""); //頁碼
param.Add("pageSize", ""); //獲取條數(最多15條,默認10)
Dictionary<string, string> headers = null;
string result = apishop_send_request(method, url, param, headers);
if (result == "")
{
//返回內容異常,發送請求失敗
Console.WriteLine("發送請求失敗");
return;
}
Response res = new JavaScriptSerializer().Deserialize<Response>(result);
if (res.statusCode == "000000")
{
//狀態碼為000000, 說明請求成功
Console.WriteLine(string.Format("請求成功: {0}", result));
}
else
{
//狀態碼非000000, 說明請求失敗
Console.WriteLine(string.Format("請求失敗: {0}", result));
}
Console.ReadLine();
}
}
}
(4)基於Java的 獲取繞口令列表 API服務請求的代碼示例
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 接口地址
* param requestMethod 請求方式
* param params 傳遞參數 重點:參數值需要用Base64進行轉碼
* return InputStream 返回結果
*/
public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params){
InputStream is = null;
try{
String parameters = "";
boolean hasParams = false;
// 將參數集合拼接成特定格式,如name=zhangsan&age=24
for (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);
}
// 請求方式是否為get
boolean isGet = "get".equalsIgnoreCase(requestMethod);
// 請求方式是否為post
boolean isPost = "post".equalsIgnoreCase(requestMethod);
if (isGet){
url += "?" + parameters;
}
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
// 請求的參數類型(使用restlet框架時,為了兼容框架,必須設置Content-Type為“”空)
conn.setRequestProperty("Content-Type", "application/octet-stream");
//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 設置連接超時時間
conn.setConnectTimeout(50000);
// 設置讀取返回內容超時時間
conn.setReadTimeout(50000);
// 設置向HttpURLConnection對象中輸出,因為post方式將請求參數放在http正文內,因此需要設置為ture,默認false
if (isPost){
conn.setDoOutput(true);
}
// 設置從HttpURLConnection對象讀入,默認為true
conn.setDoInput(true);
// 設置是否使用緩存,post方式不能使用緩存
if (isPost){
conn.setUseCaches(false);
}
// 設置請求方式,默認為GET
conn.setRequestMethod(requestMethod);
// post方式需要將傳遞的參數輸出到conn對象中
if (isPost){
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(parameters);
dos.flush();
dos.close();
}
// 從HttpURLConnection對象中讀取響應的消息
// 執行該語句時才正式發起請求
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", ""); //頁碼
params.put("pageSize", ""); //獲取條數(最多15條,默認10)
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"){
// 狀態碼為000000, 說明請求成功
System.out.println("請求成功:" + jsonObject.getString("result"));
}else{
// 狀態碼非000000, 說明請求失敗
System.out.println("請求失敗:" + jsonObject.getString("desc"));
}
}else{
// 返回內容異常,發送請求失敗,以下可根據業務邏輯自行修改
System.out.println("發送請求失敗");
}
}
}
知識類API調用的代碼示例合集:駕考題庫、ISBN書號查詢、萬年歷查詢等