# 代码示例

  • cURL command line
curl -H "accept: application/json" -d "apiKey= ${your_api_key}" -G https://api.xcurrency.com/rate/mid/coins
  • Python
# This example uses Python 3.7

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, ToomanyRedirects
import json

url = 'https://api.xcurrency.com/rate/mid/coins'
parameters = {
	'apiKey': 'your_api_key'
}
headers = {
	'Accepts': 'application/json'
}

session = Session()
session.headers.update(headers)

try:
	response = session.get(url, params = parameters)
	data = json.loads(response.text)
except (ConnectionError, Timeout, TooManyRedirects) as e:
	print(e)
  • Golang
package main

import (
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
  "net/url"
  "os"
)

func main() {
  client := &http.Client{}
  req, err := http.NewRequest("GET","https://api.xcurrency.com/rate/mid/coins", nil)
  if err != nil {
    log.Print(err)
    os.Exit(1)
  }

  q := url.Values{}
  q.Add("apiKey", "your_api_key")

  req.Header.Set("Accepts", "application/json")
  req.URL.RawQuery = q.Encode()

  resp, err := client.Do(req);
  if err != nil {
    fmt.Println("Error sending request to server")
    os.Exit(1)
  }
  fmt.Println(resp.Status);
  respBody, _ := ioutil.ReadAll(resp.Body)
  fmt.Println(string(respBody));

}
  • PHP
/**
 * Requires curl enabled in php.ini
 **/

<?php
$url = 'https://api.xcurrency.com/rate/mid/coins';
$parameters = [
  'apiKey' => 'your_api_key'
];

$headers = [
  'Accepts: application/json'
];
$qs = http_build_query($parameters); // query string encode the parameters
$request = "{$url}?{$qs}"; // create the request URL

$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
  CURLOPT_URL => $request,            // set the request URL
  CURLOPT_HTTPHEADER => $headers,     // set the headers 
  CURLOPT_RETURNTRANSFER => 1         // ask for raw response instead of bool
));

$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response)); // print json decoded response
curl_close($curl); // Close request
?>
  • Java
/** 
 * This example uses the Apache HTTPComponents library. 
 */

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class JavaExample {

  private static String apiKey = "you_api_key";

  public static void main(String[] args) {
    String uri = "https://api.xcurrency.com/rate/mid/coins";
    List<NameValuePair> paratmers = new ArrayList<NameValuePair>();
    paratmers.add(new BasicNameValuePair("apiKey", apiKey));

    try {
      String result = makeAPICall(uri, paratmers);
      System.out.println(result);
    } catch (IOException e) {
      System.out.println("Error: cannont access content - " + e.toString());
    } catch (URISyntaxException e) {
      System.out.println("Error: Invalid URL " + e.toString());
    }
  }

  public static String makeAPICall(String uri, List<NameValuePair> parameters)
      throws URISyntaxException, IOException {
    String response_content = "";

    URIBuilder query = new URIBuilder(uri);
    query.addParameters(parameters);

    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet request = new HttpGet(query.build());

    request.setHeader(HttpHeaders.ACCEPT, "application/json");

    CloseableHttpResponse response = client.execute(request);

    try {
      System.out.println(response.getStatusLine());
      HttpEntity entity = response.getEntity();
      response_content = EntityUtils.toString(entity);
      EntityUtils.consume(entity);
    } finally {
      response.close();
    }

    return response_content;
  }

}
  • Node.js
/* Example in Node.js ES6 using request-promise */

const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://api.xcurrency.com/rate/mid/coins',
  qs: {
    'apiKey': 'your_api_key'
  },
  headers: {
    'ACCEPT': 'application/json'
  },
  json: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response);
}).catch((err) => {
  console.log('API call error:', err.message);
});