Я пытаюсь создать взаимодействие сервера и клиента на микроконтроллере ESP32. Он будет состоять из простого HTTP-сервера и клиента. Таким образом, клиент отправит запрос POST на сервер, и сервер выполнит некоторую логику с полученными данными.
И для большего контекста вот сервер: побочный код:
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
int contentLength = header.indexOf("Content-Length: ");
if (contentLength != -1) {
contentLength = header.substring(contentLength + 16).toInt();
int bodyRead = 0;
while (bodyRead < contentLength && client.available()) {
char c = client.read();
requestBody += c;
bodyRead++;
}
}
// Separate direction and vehicle id
int sd = requestBody.indexOf('=');
int vd = requestBody.indexOf('&');
String direction = requestBody.substring(sd + 1, vd);
int pos = requestBody.indexOf('=', vd);
String vehicle = requestBody.substring(pos + 1);
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println("Got it, " + direction + " for : " + vehicle);
client.println();
Serial.println("Request Body : " + requestBody);
Serial.println("Direction : " + direction);
Serial.println("Vehicle : " + vehicle);
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
А вот код на стороне клиента:
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "from=south&id=military";
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
Теперь проблема в том, что сервер не может правильно прочитать запрос POST.
И прежде чем тестировать клиент, я использую API Тестер (мобильное приложение) для проверки сервера, и он работает как положено. Итак, мой сервер распечатывает их на последовательном мониторе:
POST / HTTP/1.1
user-agent: apitester.org Android/7.5(641)
accept: */*
Content-Type: application/x-www-form-urlencoded
Content-Length: 22
Host: 192.168.4.1
Connection: Keep-Alive
Accept-Encoding: gzip
Request Body : from=south&id=military
Direction : south
Vehicle : military
Client disconnected.
Но когда я отправляю запрос POST от клиента, мой сервер не возвращает никаких данных на последовательный монитор:
POST / HTTP/1.1
Host: 192.168.4.1
User-Agent: ESP32HTTPClient
Connection: keep-alive
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 23
Request Body :
Direction :
Vehicle :
Client disconnected.
Я до сих пор не понял, почему это происходит. Я так понимаю ошибка на стороне клиента? Потому что сервер работает при использовании с API Tester. Но судя по многим руководствам, которые я прочитал, мой клиентский код должен работать правильно.
Кроме того, поскольку нет чего-то вроде кода ошибки, я не знаю, где мне это исправить. проблема. Надеюсь, вы сможете мне в этом помочь.
[EDIT]:
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// Serial.print("STATUS REPORT : ");
// Serial.println(header);
// Find the Content-Length header
int contentLength = header.indexOf("Content-Length: ");
if (contentLength != -1) {
Serial.print("STATUS REPORT : ");
Serial.println(contentLength);
// Find the end of the Content-Length line
int endOfContentLength = header.indexOf("\r\n", contentLength);
Serial.print("STATUS REPORT : ");
Serial.println(endOfContentLength);
if (endOfContentLength != -1) {
// Extract the Content-Length value as an integer
contentLength = header.substring(contentLength + 16, endOfContentLength).toInt();
int bodyRead = 0;
while (bodyRead < contentLength && client.available()) {
if (client.available()) {
char c = client.read();
requestBody += c;
bodyRead++;
}
}
}
}
// Separate direction and vehicle id
int sd = requestBody.indexOf('=');
int vd = requestBody.indexOf('&');
String direction = requestBody.substring(sd + 1, vd);
int pos = requestBody.indexOf('=', vd);
String vehicle = requestBody.substring(pos + 1);
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/plain");
client.println("Connection: close");
client.println();
client.println("Got it, " + direction + " for : " + vehicle);
Serial.println("Request Body : " + requestBody);
Serial.println("Direction : " + direction);
Serial.println("Vehicle : " + vehicle);
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... y-on-esp32
Как правильно прочитать тело POST REQUEST на ESP32? ⇐ C++
Программы на C++. Форум разработчиков
-
Anonymous
1711855891
Anonymous
Я пытаюсь создать взаимодействие сервера и клиента на микроконтроллере ESP32. Он будет состоять из простого HTTP-сервера и клиента. Таким образом, клиент отправит запрос POST на сервер, и сервер выполнит некоторую логику с полученными данными.
И для большего контекста вот сервер: побочный код:
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
int contentLength = header.indexOf("Content-Length: ");
if (contentLength != -1) {
contentLength = header.substring(contentLength + 16).toInt();
int bodyRead = 0;
while (bodyRead < contentLength && client.available()) {
char c = client.read();
requestBody += c;
bodyRead++;
}
}
// Separate direction and vehicle id
int sd = requestBody.indexOf('=');
int vd = requestBody.indexOf('&');
String direction = requestBody.substring(sd + 1, vd);
int pos = requestBody.indexOf('=', vd);
String vehicle = requestBody.substring(pos + 1);
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println("Got it, " + direction + " for : " + vehicle);
client.println();
Serial.println("Request Body : " + requestBody);
Serial.println("Direction : " + direction);
Serial.println("Vehicle : " + vehicle);
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
А вот код на стороне клиента:
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "from=south&id=military";
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
Теперь проблема в том, что сервер не может правильно прочитать запрос POST.
И прежде чем тестировать клиент, я использую API Тестер (мобильное приложение) для проверки сервера, и он работает как положено. Итак, мой сервер распечатывает их на последовательном мониторе:
POST / HTTP/1.1
user-agent: apitester.org Android/7.5(641)
accept: */*
Content-Type: application/x-www-form-urlencoded
Content-Length: 22
Host: 192.168.4.1
Connection: Keep-Alive
Accept-Encoding: gzip
Request Body : from=south&id=military
Direction : south
Vehicle : military
Client disconnected.
Но когда я отправляю запрос POST от клиента, мой сервер не возвращает никаких данных на последовательный монитор:
POST / HTTP/1.1
Host: 192.168.4.1
User-Agent: ESP32HTTPClient
Connection: keep-alive
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 23
Request Body :
Direction :
Vehicle :
Client disconnected.
Я до сих пор не понял, почему это происходит. Я так понимаю ошибка на стороне клиента? Потому что сервер работает при использовании с API Tester. Но судя по многим руководствам, которые я прочитал, мой клиентский код должен работать правильно.
Кроме того, поскольку нет чего-то вроде кода ошибки, я не знаю, где мне это исправить. проблема. Надеюсь, вы сможете мне в этом помочь.
[EDIT]:
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// Serial.print("STATUS REPORT : ");
// Serial.println(header);
// Find the Content-Length header
int contentLength = header.indexOf("Content-Length: ");
if (contentLength != -1) {
Serial.print("STATUS REPORT : ");
Serial.println(contentLength);
// Find the end of the Content-Length line
int endOfContentLength = header.indexOf("\r\n", contentLength);
Serial.print("STATUS REPORT : ");
Serial.println(endOfContentLength);
if (endOfContentLength != -1) {
// Extract the Content-Length value as an integer
contentLength = header.substring(contentLength + 16, endOfContentLength).toInt();
int bodyRead = 0;
while (bodyRead < contentLength && client.available()) {
if (client.available()) {
char c = client.read();
requestBody += c;
bodyRead++;
}
}
}
}
// Separate direction and vehicle id
int sd = requestBody.indexOf('=');
int vd = requestBody.indexOf('&');
String direction = requestBody.substring(sd + 1, vd);
int pos = requestBody.indexOf('=', vd);
String vehicle = requestBody.substring(pos + 1);
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/plain");
client.println("Connection: close");
client.println();
client.println("Got it, " + direction + " for : " + vehicle);
Serial.println("Request Body : " + requestBody);
Serial.println("Direction : " + direction);
Serial.println("Vehicle : " + vehicle);
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78245674/how-to-correctly-read-post-request-body-on-esp32[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия