我正在尝试通过ESP8266发送HTTPS POST请求。当我使用ESP尝试不起作用时,我可以使用python和cURL来使请求很好。我的代码段位于下面
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代码,我将非常感激。谢谢
答案 0 :(得分:2)
您的代码中有一些错误。
以下是发送http(不使用String)的示例:
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 :(得分:0)
一般建议:使用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");
注意如何
Host
只是“ api.pushbullet.com” 旁注:
Content-Length
发送正确的值HTTPClient
,如果您对底层HTTP编程不满意