解析 HTTP 响应中的 JSON 文档-Arduino(意外响应:HTTP/1.1 301 移动永久错误)

时间:2021-01-20 02:52:25

标签: json http arduino httprequest ethernet

我正在使用 Arduino 的以太网屏蔽和 Arduino mega 来解析 HTTP 响应中的 JSON 文档以读取 JSON 文件中的一些值。

JSON 地址为:https://api.coinbase.com/v2/prices/BTC-USD/spot


我收到此错误消息:

正在连接... 连接的! 意外响应:HTTP/1.1 301 已永久移动

是不是 Arduino 库没有 SSL 功能,因此无法连接到安全服务器?如果是,那么我需要你的帮助来解决这个问题。 或者我可能需要使用另一个与 https 相关的端口?


这是我的代码:

#include <ArduinoJson.h>
#include <Ethernet.h>
#include <SPI.h>

void setup() {
  // Initialize Serial port
  Serial.begin(9600);
  while (!Serial) continue;

  // Initialize Ethernet library
  byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  if (!Ethernet.begin(mac)) {
    Serial.println(F("Failed to configure Ethernet"));
    return;
  }
  delay(1000);

  Serial.println(F("Connecting..."));

  // Connect to HTTP server
  EthernetClient client;
  client.setTimeout(10000);
  if (!client.connect("api.coinbase.com", 80)) {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("Connected!"));

  // Send HTTP request
  client.println(F("GET /v2/prices/BTC-USD/spot/response.json HTTP/1.0"));
  client.println(F("Host: api.coinbase.com"));
  client.println(F("Connection: close"));
  if (client.println() == 0) {
    Serial.println(F("Failed to send request"));
    return;
  }

  // Check HTTP status
  char status[32] = {0};
  client.readBytesUntil('\r', status, sizeof(status));
  // It should be "HTTP/1.0 200 OK" or "HTTP/1.1 200 OK"
  if (strcmp(status + 9, "200 OK") != 0) {
    Serial.print(F("Unexpected response: "));
    Serial.println(status);
    return;
  }

  // Skip HTTP headers
  char endOfHeaders[] = "\r\n\r\n";
  if (!client.find(endOfHeaders)) {
    Serial.println(F("Invalid response"));
    return;

// the rest of the code related to parsing that I didn't paste for the sake the argument. 

谢谢大家。

0 个答案:

没有答案
相关问题