我正在尝试从 API 端点获取一些详细信息(https://bitcoin-ethereum-price-test.vercel.app/btc)。但每次它都返回 false (-1)。当我在浏览器上获取端点时,它只是工作 fin,返回 200。
http.GET()
返回 -1
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Wire.h>
WiFiClient wifiClient;
void setup() {
Serial.begin(9600);
WiFi.begin("56", "emayush56");
while(WiFi.status() != WL_CONNECTED)
{
delay(200);
Serial.print("..");
}
Serial.println();
Serial.println("NodeMCU is connected!");
Serial.println(WiFi.localIP());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(wifiClient, "https://bitcoin-ethereum-price-test.vercel.app/btc");
int httpCode = http.GET();
Serial.println("*** RESPONSE STATUS ***");
Serial.println(httpCode);
if (httpCode > 0) {
String payload = http.getString();
Serial.println(payload);
}
http.end();
}
delay(3000);
}
我认为我做错了
http.begin()
或其他事情。 http.begin() 可以通过两种不同的方式调用:
类型1: bool begin(WiFiClient &client, const String& url);
类型2: bool begin(WiFiClient &client, const String& 主机, uint16_t 端口, const String& uri = "/", bool https = false);
我已经尝试过这两种方法 - 首先直接传递 WifiClient 对象和 URL(类型 1),然后(类型 2)传递 WiFiClient 对象和其他参数。
如果我的主要 api 端点(https://bitcoin-ethereum-price-test.vercel.app/btc)返回 200 那么为什么 http.GET() 返回 false?请帮我找出问题所在。
您正在向 HTTPS API 发出 HTTP 请求。您将需要使用证书的 sha1 指纹。您可以通过单击 URL 开头的小锁来获取 Chrome 中的指纹,转到“连接安全”选项,然后选择“证书有效”,它会向您显示有关证书的一些信息以及密钥底部。
以下是我发现的一些示例代码,它将 HTTPS 与 HTTPClient 库结合使用:\
void loop() {
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
Serial.print("[HTTPS] begin...\n");
http.begin("https://some.secure_server.com/auth/authorise", "2F 2A BB 23 6B 03 89 76 E6 4C B8 36 E4 A6 BF 84 3D DA D3 9F");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST("user_id=mylogin&user_password=this%20is%20my%20%24ecret%20pa%24%24word");
if (httpCode > 0) {
http.writeToStream(&Serial);
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] ... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] ... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(10000);
}
如果没有“content-length”标头,http.getSize() 将返回 -1。某些响应代码(例如 204)可能会发生这种情况,其中不应返回任何数据。打印出您的响应代码,看看为什么您没有收到任何数据,因此省略了“内容长度”字段。