以下示例代碼適用于 www.apishop.net 網站下的API,使用本文提及的接口調用代碼示例前,您需要先申請相應的API服務。
- 六位圖片驗證碼生成:包括純數字、小寫字母、大寫字母、大小寫混合、數字+小寫、數字+大寫、數字+大小寫等情況。
- 四位圖片驗證碼生成:包括純數字、小寫字母、大寫字母、大小寫混合、數字+小寫、數字+大寫、數字+大小寫等情況。
- 簡單驗證碼識別:驗證碼類型 : 數字+字母, 純英文, 純數字,計算題
- 英數_驗證碼識別:純數字,純英文,數字+英文
- 中英數_驗證碼識別:英文、數字、中文或混合型
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/checkcode/recognizeVerifyCodeComplicate";
$headers = NULL;
$params = array("convertJPG" => "", //是否轉換成jpg格式(有少量png或gif圖轉成jpg格式后識別率明顯提高,但并不是所有png或gif轉成jpg后都會提高識別率。) 此字段為1時表示需要把圖片轉為jpg格式,其他值不做轉換操作。"imgBASE64" => "", //圖片文件的base64字符串。圖片大小需要小于100KB。"codeType" => "", //驗證碼類型,最大長度為10.(10:任意長度數字(成功率有所降低),11~19:1~9位數字,20:任意長度英文(成功率有所降低),21~29:1~9位英文,30:任意長度英數混合(成功率有所降低),31~39:1~9位英數混合,40:任意長度漢字(成功率有所降低),41~49:1~9位漢字,50:任意長度中英數混合(成功率有所降低)),如“34”代表四位英數混合
);$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 sysreload(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 Nonemethod = "POST"
url = "https://api.apishop.net/common/checkcode/recognizeVerifyCodeComplicate"
headers = None
params = { "convertJPG":"", #是否轉換成jpg格式(有少量png或gif圖轉成jpg格式后識別率明顯提高,但并不是所有png或gif轉成jpg后都會提高識別率。) 此字段為1時表示需要把圖片轉為jpg格式,其他值不做轉換操作。"imgBASE64":"", #圖片文件的base64字符串。圖片大小需要小于100KB。"codeType":"", #驗證碼類型,最大長度為10.(10:任意長度數字(成功率有所降低),11~19:1~9位數字,20:任意長度英文(成功率有所降低),21~29:1~9位英文,30:任意長度英數混合(成功率有所降低),31~39:1~9位英數混合,40:任意長度漢字(成功率有所降低),41~49:1~9位漢字,50:任意長度中英數混合(成功率有所降低)),如“34”代表四位英數混合
}
result = apishop_send_request(method=method, url=url, params=params, headers=headers)
if result:body = result.textresponse = 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/checkcode/recognizeVerifyCodeComplicate";Dictionary<string, string> param = new Dictionary<string, string>(); param.Add("convertJPG", ""); //是否轉換成jpg格式(有少量png或gif圖轉成jpg格式后識別率明顯提高,但并不是所有png或gif轉成jpg后都會提高識別率。) 此字段為1時表示需要把圖片轉為jpg格式,其他值不做轉換操作。param.Add("imgBASE64", ""); //圖片文件的base64字符串。圖片大小需要小于100KB。param.Add("codeType", ""); //驗證碼類型,最大長度為10.(10:任意長度數字(成功率有所降低),11~19:1~9位數字,20:任意長度英文(成功率有所降低),21~29:1~9位英文,30:任意長度英數混合(成功率有所降低),31~39:1~9位英數混合,40:任意長度漢字(成功率有所降低),41~49:1~9位漢字,50:任意長度中英數混合(成功率有所降低)),如“34”代表四位英數混合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=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);}// 請求方式是否為getboolean isGet = "get".equalsIgnoreCase(requestMethod);// 請求方式是否為postboolean 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,默認falseif (isPost){conn.setDoOutput(true);}// 設置從HttpURLConnection對象讀入,默認為trueconn.setDoInput(true);// 設置是否使用緩存,post方式不能使用緩存if (isPost){conn.setUseCaches(false);}// 設置請求方式,默認為GETconn.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/checkcode/recognizeVerifyCodeComplicate";String requestMethod = "POST";Map<String, String> params = new HashMap<String, String>(); params.put("convertJPG", ""); //是否轉換成jpg格式(有少量png或gif圖轉成jpg格式后識別率明顯提高,但并不是所有png或gif轉成jpg后都會提高識別率。) 此字段為1時表示需要把圖片轉為jpg格式,其他值不做轉換操作。params.put("imgBASE64", ""); //圖片文件的base64字符串。圖片大小需要小于100KB。params.put("codeType", ""); //驗證碼類型,最大長度為10.(10:任意長度數字(成功率有所降低),11~19:1~9位數字,20:任意長度英文(成功率有所降低),21~29:1~9位英文,30:任意長度英數混合(成功率有所降低),31~39:1~9位英數混合,40:任意長度漢字(成功率有所降低),41~49:1~9位漢字,50:任意長度中英數混合(成功率有所降低)),如“34”代表四位英數混合 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("發送請求失敗");}}
}
復制代碼