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.
- Long distance bus inquiry: national major city coach time inquiry, bus station inquiry
- Models: including car brand, car, car model
- Train ticket inquiry: provide national train ticket, train station and train ticket inquiries
- National oil price query: support national 5 standard, can query the oil price of 31 provinces.
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 API for getting today’s oil price as an example:
(1) Based on PHP to get today’s oil price API service request code example
<? php$method = "POST";
$url = "https://api.apishop.net/common/oil/getOilPriceToday";
$headers = NULL;
$params = array(
"province"= >"", // The name of the province, such as Guangxi, Beijing (if you do not input, the oil price of 31 provinces will be returned);$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 code sample to get today’s oil price API service request
#! /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/oil/getOilPriceToday"
headers = None
params = {
"province":"".# Name of province, such as Guangxi, Beijing (if no input, return the oil price of 31 provinces in China)
}
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 sample based on C# to get today’s oil price 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 {/** * 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/oil/getOilPriceToday";
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("province".""); // the name of the province, such as The name of The province, such as Beijing, is returned. 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 obtain today’s oil price 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/oil/getOilPriceToday";
String requestMethod = "POST";
Map<String, String> params = new HashMap<String, String>();
params.put("province".""); String result = null; // Province name, such as Guangxi or Beijing. 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