Token更新机制调用案例

更新时间:2024-03-29 15:30:00

1. 授权参数

Authorization: Bearer {API TOKEN}

其中 {API TOKEN} 是你在太空地图创建的API令牌。该 token 在后续的 API 请求中用于身份验证。

2. Python 调用示例

            
  import requests
  # 设置授权头
  headers = {
      "Authorization": "Bearer {API TOKEN}"
  }
  
  # 获取当前用户的 token 状态
  response = requests.post("http://spacemapper.cn/cgi/token/check", 
                          json={}, 
                          headers=headers)
  data = response.json()
  
  if data['code'] == 0 and data['data']['shouldBeUpdated'] == 1:
      # 令牌需要更新,调用创建接口
      create_response = requests.post("http://spacemapper.cn/cgi/token/create",
                                     json={},
                                     headers=headers)
      new_token = create_response.json()['data']['token']
      print("新令牌已创建:", new_token)
  else:
      print("令牌无需更新")

3. Java 调用示例

                
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.impl.client.HttpClients;
  import org.apache.http.impl.client.CloseableHttpClient;
  import org.apache.http.entity.StringEntity;
  import org.apache.http.util.EntityUtils;
  
  public class TokenUpdateExample {
      public static void main(String[] args) {
          try (CloseableHttpClient client = HttpClients.createDefault()) {
              HttpPost post = new HttpPost("http://spacemapper.cn/cgi/token/check");
              post.setEntity(new StringEntity("{}"));
              post.setHeader("Authorization", "Bearer {API TOKEN}");
              
              String responseString = EntityUtils.toString(client.execute(post).getEntity());
              if (responseString.contains("\"code\": 0") && 
                  responseString.contains("\"shouldBeUpdated\": 1")) {
                  HttpPost createPost = new HttpPost("http://spacemapper.cn/cgi/token/create");
                  createPost.setHeader("Authorization", "Bearer {API TOKEN}");
                  String createResponse = EntityUtils.toString(client.execute(createPost).getEntity());
                  System.out.println("新令牌已创建:" + createResponse);
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }

4. C# 调用示例

                
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;
  using Newtonsoft.Json.Linq;
  
  class Program {
      static async Task Main() {
          using HttpClient client = new HttpClient();
          client.DefaultRequestHeaders.Add("Authorization", "Bearer {API TOKEN}");
          
          var response = await client.PostAsync("http://spacemapper.cn/cgi/token/check",
              new StringContent("{}", Encoding.UTF8, "application/json"));
          
          JObject data = JObject.Parse(await response.Content.ReadAsStringAsync());
          if (data["code"]?.ToString() == "0" && data["data"]?["shouldBeUpdated"]?.ToString() == "1") {
              var createResponse = await client.PostAsync("http://spacemapper.cn/cgi/token/create", 
                  new StringContent("{}", Encoding.UTF8, "application/json"));
              Console.WriteLine("新令牌已创建: " + await createResponse.Content.ReadAsStringAsync());
          }
      }
  }

5. C++ 调用示例

                
  #include <iostream>
  #include <string>
  #include <curl/curl.h>
  
  size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
      ((std::string*)userp)->append((char*)contents, size * nmemb);
      return size * nmemb;
  }
  
  int main() {
      CURL *curl = curl_easy_init();
      if(curl) {
          struct curl_slist *headers = NULL;
          headers = curl_slist_append(headers, "Authorization: Bearer {API TOKEN}");
          
          std::string response;
          curl_easy_setopt(curl, CURLOPT_URL, "http://spacemapper.cn/cgi/token/check");
          curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
          curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{}");
          curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
          curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
          
          if(curl_easy_perform(curl) == CURLE_OK) {
              if(response.find("\"shouldBeUpdated\": 1") != std::string::npos) {
                  curl_easy_setopt(curl, CURLOPT_URL, "http://spacemapper.cn/cgi/token/create");
                  curl_easy_perform(curl);
              }
          }
          curl_easy_cleanup(curl);
      }
      return 0;
  }

6. Node.js 调用示例

                
                
const axios = require('axios');
// 设置API请求的URL和Authorization token
const apiUrl = 'https://spacemapper.cn/cgi/token/check';
const apiToken = 'your-api-token-here'; // 在此处替换为您的API Token

// 检查令牌是否需要更新
axios.post(apiUrl, {}, {
  headers: {
    'Authorization': `Bearer ${apiToken}`
  }
})
.then(response => {
  // 响应示例
  const data = response.data;
  if (data.code === 0) {
    // 令牌需要更新
    if (data.data.shouldBeUpdated === 1) {
      console.log('Token needs to be updated.');
      // 调用创建新令牌的接口
      return axios.post('https://spacemapper.cn/cgi/token/create', {}, {
        headers: {
          'Authorization': `Bearer ${apiToken}`
        }
      });
    } else {
      console.log('Token is still valid.');
    }
  } else {
    console.log('Failed to check token status.');
  }
})
.then(createResponse => {
  if (createResponse) {
    const newToken = createResponse.data.data.token;
    console.log('New token created:', newToken);
    // 使用新 token 进行后续请求
  }
})
.catch(error => {
  console.error('Error:', error);
});


7. CURL 调用示例

    
    
# 检查令牌状态
curl -X POST "http://spacemapper.cn/cgi/token/check" \
  -H "Authorization: Bearer {API TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{}'

# 当shouldBeUpdated=1时创建新令牌
curl -X POST "http://spacemapper.cn/cgi/token/create" \
  -H "Authorization: Bearer {API TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{}'

# 带错误处理的完整示例
response=$(curl -s -X POST "http://spacemapper.cn/cgi/token/check" \
  -H "Authorization: Bearer {API TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{}')

should_update=$(echo $response | grep -o '"shouldBeUpdated": 1')
if [ -n "$should_update" ]; then
  new_token=$(curl -s -X POST "http://spacemapper.cn/cgi/token/create" \
    -H "Authorization: Bearer {API TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{}' | grep -o '"token":"[^"]*' | cut -d'"' -f4)
  echo "New token: $new_token"
else
  echo "No need to update"
fi