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.
- A six-digit image verification code can be generated, including pure digits, lowercase letters, uppercase letters, uppercase letters, digits + lowercase letters, digits + uppercase letters, and digits + case.
- A four-digit image verification code can be generated, including pure digits, lowercase letters, uppercase letters, uppercase letters, digits + lowercase letters, digits + uppercase letters, and digits + case.
- Simple verification code identification: Verification code type: numbers + letters, pure English, pure numbers, calculation questions
- Digit _ Verification code identification: Pure digits, pure English, digits + English
- Chinese number _ Verification code identification: English, numeric, Chinese, or a combination of them
- Two-dimensional code codec: Supports generation and identification of two-dimensional code. When the TWO-DIMENSIONAL code is generated, the generated two-dimensional code picture is directly returned
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 in PHP, Python, C#, and Java. Take the two-dimensional code generation API as an example:
(1) Code example of PHP based TWO-DIMENSIONAL code generation API service request
<? php$method = "POST";
$url = "https://api.apishop.net/common/qrcode/content2QrCode";
$headers = NULL;
$params = array(
"content"= >""/ / content"size"= >"", // Image size (range: 1~10), default is 4"level"= >"", // Fault tolerance (0:L,1:M,:2:H,3:Q), default is 0"margin"= >"", // Border size (range: 1-10), default: 3);$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) Code example of generating API service request based on Python two-dimensional code
#! /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/qrcode/content2QrCode"
headers = None
params = {
"content":"".# content
"size":"".# Image size (range: 1~10), default is 4
"level":"".# error tolerance (0:L,1:M,:2:H,3:Q), defaults to 0
"margin":"".# Border size (range: 1 to 10), default is 3
}
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) code example of generating API service request based on C# two-dimensional code
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/qrcode/content2QrCode";
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("content".""); / / contents param. Add ("size".""); // Image size (range: 1~10), default is 4"level".""); // Error tolerance (0:L,1:M,:2:H,3:Q), default is 0 param.add ()"margin".""); // Frame size (range: 1 to 10), default: 3 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) Code examples of Java based TWO-DIMENSIONAL code generation 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 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/qrcode/content2QrCode";
String requestMethod = "POST";
Map<String, String> params = new HashMap<String, String>();
params.put("content".""); / / contents params. Put ("size".""); // Image size (range: 1~10), default is 4"level".""); // Error tolerance (0:L,1:M,:2:H,3:Q), default is 0 params.put("margin".""); // Border size (range: 1 to 10), default is 3 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