我目前正在ESP32上使用以下Arduino代码(我已经取出了不相关的部分)从服务器上为二进制文件发出https请求,以存储在SPIFFS中。但是我现在需要设置一个自定义报头,因此需要使用http . beginrequest()方法。但这种方法不采用WiFiClientSecure引用,所以我不能使用HTTPS。标准Arduino库实际上可以使用自定义头执行https请求,还是有另一个库?
WiFiClientSecure client;
client.setInsecure(); // Not using certificate check while testing
HTTPClient https;
https.useHTTP10(true);
Serial.println("https.begin...");
if (https.begin(client, "https://path.to.binary.file")) { // HTTPS
Serial.println("Sending GET request...");
//https.sendHeader("X-device: 12345678"); // Cannot use here
// start connection and send HTTP header
int httpCode=https.GET();
Serial.printf("Response code: %un",httpCode);
Serial.printf("Content length: %un",https.getSize());
uint32_t bytesRead=0;
uint8_t b;
while(client.connected()){
while(client.available()){
++bytesRead;
b=client.read();
Serial.printf("0x%02x ",b);
if((bytesRead%16)==0){
Serial.println();
}
}
}
Serial.printf("nBytes read: %un",bytesRead);
https.end();
}else{
Serial.println("Could not connect to server");
}
http . sendheader ("X-device: 12345678");
https.sendHeader()
不添加头,因为你认为它是,它实际上发送所有的头(除了正文)从GET / HTTP/1.1
开始,直到http头和http正文之间的分隔符,见源代码。
为http请求添加自定义报头,您需要使用
调用http. addheader ()https.addHeader("X-device", "12345678");
下面是应该工作的代码:
void loop() {
WiFiClientSecure client;
client.setInsecure(); // Not using certificate check while testing
HTTPClient https;
https.useHTTP10(true);
Serial.println("https.begin...");
if (https.begin(client, "https://httpbin.org/get")) { // HTTPS
Serial.println("Sending GET request...");
https.addHeader("X-device", "12345678");
int httpCode=https.GET();
Serial.printf("Response code: %un",httpCode);
Serial.printf("Content length: %un",https.getSize());
Serial.println("HTTP response:");
Serial.println(https.getString());
https.end();
}else{
Serial.println("Could not connect to server");
}
while(1);
}
此代码将返回来自https://httpbin.org/get的响应,该响应基本上回显发送/添加的所有标头,加上客户端IP和请求URL:
https.begin...
Sending GET request...
Response code: 200
Content length: 265
{
"args": {},
"headers": {
"Host": "httpbin.org",
"User-Agent": "ESP32HTTPClient",
"X-Amzn-Trace-Id": "Root=1-64392c39-768ce2a95ca639bc0f79e256",
"X-Device": "12345678"
},
"origin": "xxx.xx.xx.xx",
"url": "https://httpbin.org/get"
}
仅仅将此添加为文档是不正确的。https.addHeader()
方法可以在调用GET之前使用,并且确实有效。官方文档指出,它只能在beginRequest
和endRequest
调用之间使用。