A collection of code examples of API calls for travel services: long distance bus query, train ticket query, etc

Keywords: Java PHP Python github

The following example code applies to www.apishop.net For the API under the website, you need to apply for the corresponding API service before using the interface call code examples mentioned in this article.

  1. Coach query Long distance bus time query and bus station query in major cities in China
  2. Vehicle Daquan : including automobile brand, series and model
  3. Train ticket inquiry : provide inquiry of national train tickets, train stations and train surplus tickets
  4. National oil price inquiry : in support of the national five standards, the oil prices of 31 provinces can be inquired.

API Shop (apishop.net) provides up to 50 commonly used third-party APIs. You can download the code sample collection from github: https://github.com/apishop/All-APIs

The above interfaces contain code examples of PHP, Python, C ා and Java. Take the API of today's oil price as an example:

(1) Code example of getting API service request of today's oil price based on PHP

<?php
$method = "POST";
$url = "https://api.apishop.net/common/oil/getOilPriceToday";
$headers = NULL;
$params = array(
    "province" => "", //Province name, such as Guangxi and Beijing (if it is not inputted, the oil price of 31 provinces in China 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") {
        //The status code is 000000, indicating that the request is successful
        echo "Request succeeded:" . $result["body"];
    } else {
        //The status code is not 000000, indicating that the request failed
        echo "Request failed:" . $result["body"];
    }
} else {
    //The content returned is abnormal. Sending the request failed. The following can be modified according to the business logic
    echo "Send request failed";
}

/**
 * Forward request to destination host
 * @param $method string Request method
 * @param $URL string Request address
 * @param null $headers Request header
 * @param null $param Request parameters
 * @return array|bool
 */
function apishop_curl(&$method, &$URL, &$headers = NULL, &$param = NULL)
{
    // Initialize request
    $require = curl_init($URL);
    // Determine whether HTTPS
    $isHttps = substr($URL, 0, 8) == "https://" ? TRUE : FALSE;
    // Set request method
    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 is set in the certificate
        curl_setopt($require, CURLOPT_SSL_VERIFYHOST, 2);
    }
    if ($headers) {
        // Set request header
        curl_setopt($require, CURLOPT_HTTPHEADER, $headers);
    }
    // Return result is not output directly
    curl_setopt($require, CURLOPT_RETURNTRANSFER, TRUE);
    // redirect
    curl_setopt($require, CURLOPT_FOLLOWLOCATION, TRUE);
    // Include the return header in the output
    curl_setopt($require, CURLOPT_HEADER, TRUE);
    // Send request
    $response = curl_exec($require);
    // Get head length
    $headerSize = curl_getinfo($require, CURLINFO_HEADER_SIZE);
    // Close request
    curl_close($require);
    if ($response) {
        // Return header string
        $header = substr($response, 0, $headerSize);
        // Return 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]);
        // Turn the returned 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 {
        return FALSE;
    }
}

(2) Code example of getting API service request of today's oil price based on Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Test environment: python2.7
# Install requests dependency = > PIP install requests/ easy install requests

# Import requests dependency
import requests
import json
import sys

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

def apishop_send_request(method, url, params=None, headers=None):
    '''
    //Forward request to destination host
    @param method str Request method
    @param url str Request address
    @param params dict Request parameters
    @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":"", #Province name, such as Guangxi and Beijing (if it is not inputted, the oil price of 31 provinces in China will be returned)
}
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'):
        # The status code is 000000, indicating that the request is successful
        print('Request successful:%s' % (body,))
    else:
        # The status code is not 000000, indicating that the request failed
        print('request was aborted: %s' % (body,))
else:
    # Return content exception, send request failed
    print('Send request failed')

(3) Code example of obtaining API service request of today's oil price based on C ා

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
{
    /**
     * Forward request to destination host
     * @param method string Request method
     * @param url string Request address
     * @param params Dictionary<string,string> Request parameters
     * @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 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/oil/getOilPriceToday";
            Dictionary<string, string> param = new Dictionary<string, string>();            
            param.Add("province", ""); //Name of province, such as Guangxi and Beijing (if it is not inputted, the oil price of 31 provinces in China will be returned)

            Dictionary<string, string> headers = null;
            string result = apishop_send_request(method, url, param, headers);
            if (result == "")
            {
                //Return content exception, send request failed
                Console.WriteLine("Send request failed");
                return;
            }

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

(4) Java based code example for obtaining today's oil price 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 Access remote interface tools
*/
public class Api
{
    /**
    * Method body description: initiates a request to the remote interface and returns the byte stream type result
    * param url Interface address
    * param requestMethod Request mode
    * param params Key points of passing parameters: the parameter value needs to be transcoded with Base64
    * return InputStream Return result
    */
    public static InputStream httpRequestToStream(String url, String requestMethod, Map<String, String> params){
        InputStream is = null;
        try{
            String parameters = "";
            boolean hasParams = false;
            // Splice parameter sets into specific formats, such as 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);
            }
            // Whether the request method is get
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            // Whether the request mode is post
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            if (isGet){
                url += "?" + parameters;
            }
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            // Parameter type requested (when using restlet framework, content type must be set to "" empty in order to be compatible with framework)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // Set connection timeout
            conn.setConnectTimeout(50000);
            // Set the time-out for reading returned content
            conn.setReadTimeout(50000);
            // Set to output to the HttpURLConnection object, because the post mode places the request parameter in the http body, so it needs to be set to true, and the default is false
            if (isPost){
                conn.setDoOutput(true);
            }
            // Set to read from HttpURLConnection object, default to true
            conn.setDoInput(true);
            // Set whether to use cache or not. post mode cannot use cache
            if (isPost){
                conn.setUseCaches(false);
            }
            // Set request mode, default to GET
            conn.setRequestMethod(requestMethod);
            // post mode needs to output the passed parameters to the conn object
            if (isPost){
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(parameters);
                dos.flush();
                dos.close();
            }
            // Read the message of the response from the HttpURLConnection object
            // The request is only formally initiated when the statement is executed
            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/oil/getOilPriceToday";
        String requestMethod = "POST";
        Map<String, String> params = new HashMap<String, String>();         
        params.put("province", ""); //Province name, such as Guangxi and Beijing (if it is not inputted, the oil price of 31 provinces in China will be returned)  
        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"){
                // The status code is 000000, indicating that the request is successful
                System.out.println("Request succeeded:" + jsonObject.getString("result"));
            }else{
                // The status code is not 000000, indicating that the request failed
                System.out.println("Request failed:" + jsonObject.getString("desc"));
            }
        }else{
            // The content returned is abnormal. Sending the request failed. The following can be modified according to the business logic
            System.out.println("Send request failed");
        }
    }
}

Posted by nogeekyet on Sun, 05 Apr 2020 14:57:20 -0700