使用 ESP8266 进行 HTTPS Post 请求

问题描述 投票:0回答:2

我正在尝试使用 ESP8266 发送 HTTPS POST 请求。我可以用 python 和 cURL 很好地发出请求,只是当我用 ESP 尝试它时,它不起作用。我的一段代码如下

const char *host = "api.pushbullet.com";
const int httpsPort = 443;
const char fingerprint[] PROGMEM = "4C 70 C5 AE F3 30 E8 29 D1 9C 18 C6 2F 08 D0 6A A9 AA 19 0F";

Link = "/post";

httpsClient.print(String("POST ") + Link + " HTTP/1.1\r\n" +
               "Host: " + host + "/v2/pushes" + "\r\n" +
               "Access-Token: *************"+ "\r\n" +
               "Content-Type: application/json"+ "\r\n" +
               "Content-Length: 20"+ "\r\n" +
               "body: Hello World" + "\r\n\r\n");

Serial.println("request sent");

我想要提出的请求如下。这在 python 中工作得很好

import requests

headers = {
    'Access-Token': '***********',
    'Content-Type': 'application/json',
}
data = '{"body":"Hello World","title":"Hi","type":"note"}'
response = requests.post('https://api.pushbullet.com/v2/pushes', headers=headers, data=data)

在 cURL 中:

curl --header 'Access-Token: **********' --header 'Content-Type: application/json' --data-binary '{"body":"Hello World","title":"Hi","type":"note"}' --request POST https://api.pushbullet.com/v2/pushes

当我使用 Arduino 代码发出请求时,它返回“错误 411(需要长度)!!”。

这可能是由于我犯了一些愚蠢的错误,但如果有人可以帮助我修复我的 Arduino 代码,我将非常感激。谢谢

post https arduino esp8266 arduino-esp8266
2个回答
3
投票

您的代码中有一些错误。

  1. 您的 http POST 格式 a) 主机名、b) uri 和 c) 标头/正文分离不正确;
  2. 您的 http 正文不是有效的 json 对象。

这是发送 http 的示例(不使用字符串):

const char *host = "api.pushbullet.com";
const char *uri = "/post/v2/pushes/";
const char *body ="{\"body\": \"Hello World\"}";  // a valid jsonObject
    
char postStr[40];
sprintf(postStr, "POST %s HTTP/1.1", uri);  // put together the string for HTTP POST
    
httpsClient.println(postStr);
httpsClient.print("Host: "); httpsClient.println(host);
httpsClient.println("Access-Token: *************");
httpsClient.println("Content-Type: application/json");
httpsClient.print("Content-Length: "); httpsClient.println(strlen(body));
httpsClient.println();    // extra `\r\n` to separate the http header and http body
httpsClient.println(body);

1
投票

一般建议:当您使用

cURL
时,请始终使用
--verbose
查看完整的 HTTP 交换。

就你的情况来说应该是

httpsClient.print(String("POST ") + "/v2/pushes" + Link + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Access-Token: *************"+ "\r\n" +
               "Content-Type: application/json"+ "\r\n" +
               "Content-Length: 20"+ "\r\n" +
               "body: Hello World" + "\r\n\r\n");

注意如何

  • 路径是“/v2/pushes/”加上标识符(在您的情况下是“链接”?)
  • Host
    只是“api.pushbullet.com”

旁注:

© www.soinside.com 2019 - 2024. All rights reserved.