首页 > 解决方案 > 如何在 Arduino IDE 中向 http 请求添加标头

问题描述

这是 Arduino IDE 中不起作用的代码(httpCode = -1):

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

char ssid[] = "-------";
const char* password =  "------";

void setup() 
{
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(1000);
    Serial.println("Connecting...");
  }
}

void loop() 
{
  if (WiFi.status() == WL_CONNECTED) 
  {
    HTTPClient http; //Object of class HTTPClient
    http.begin("https://api-football-v1.p.rapidapi.com/v2/fixtures/team/33/next/10");
    http.addHeader("x-rapidapi-key", "-------");
    int httpCode = http.GET();
    Serial.println(httpCode);
    if (httpCode > 0) 
    {

      Serial.println(http.getString());

    }
    http.end(); //Close connection
  }
  delay(60000);
}

这是python中“完全相同”的代码:

import requests

url = "https://api-football-v1.p.rapidapi.com/v2/fixtures/team/33/next/10"


headers = {
    'x-rapidapi-key': "--------",
    }

response = requests.request("GET", url, headers=headers)

print(response.text)

我对在 Arduino IDE 中编程非常陌生,我现在才公平地说 python,所以我的猜测是我的代码中可能有几个错误。任何想法如何解决它?

标签: pythonarduinoarduino-ide

解决方案


我正在使用的 arduino 库不会在 GET 上发送附加标头,除非它包含在 beginRequest() 和 endRequest() 中

http.beginRequest();
http.get(request->url);
http.sendHeader("x-rapidapi-key:" + request->apiKey);;
http.endRequest();

我今天被困在这条路上太久了。


推荐阅读