I started to work with HTTPClient and the WiFly library to connect to an SSID and then send POST data to a server. When I was sending the data to my localhost, it was working on localhost, but when changing the URL to a server I am getting this response:
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>
My code is the following:
#define HTTP_POST_URL "http://URL/insert.php"
#define HTTP_POST_DATA "181"
SoftwareSerial uart(2, 3);
WiFly wifly(uart);
HTTPClient client;
char get;
while (client.post(HTTP_POST_URL, HTTP_POST_DATA, 10000) < 0) {}
Looking at the constructor of POST in the HTTPClient library it is possible to use POST without defining the header and it will automatically create a default header:
int HTTPClient::post(const char *url, const char *data, int timeout)
{
return connect(url, "POST", NULL, data, timeout);
}
int HTTPClient::post(const char url, const char headers, const char *data, int timeout)
{
return connect(url, "POST", headers, data, timeout);
}
int HTTPClient::connect(const char url, const char method, const char *data, int timeout)
{
return connect(url, method, NULL, data, timeout);
}
int HTTPClient::connect(const char url, const char method, const char headers, const char data, int timeout)
{
char host[HTTP_MAX_HOST_LEN];
uint16_t port;
char path[HTTP_MAX_PATH_LEN];
if (parseURL(url, host, sizeof(host), &port, path, sizeof(path)) != 0) {
DBG("Failed to parse URL.\r\n");
return -1;
}
if (!wifly->connect(host, port, timeout)) {
DBG("Failed to connect.\r\n");
return -2;
}
// Send request
char buf[HTTP_MAX_BUF_LEN];
snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\n", method, path);
wifly->send(buf);
// Send all headers
snprintf(buf, sizeof(buf), "Host: %s\r\nConnection: close\r\n", host);
wifly->send(buf);
if (data != NULL) {
snprintf(buf, sizeof(buf), "Content-Length: %d\r\nContent-Type: text/plain\r\n", strlen(data));
wifly->send(buf);
}
if (headers != NULL) {
wifly->send(headers);
}
// Close headers
wifly->send("\r\n");
// Send body
if (data != NULL) {
wifly->send(data);
}
return 0;
}
So I am not sure why it worked on localhost but on the hosting.
EDIT:
after logging it to console, this is the request I am sending:
POST /insert_gsr.php HTTP/1.1
Host: www.mywebsite.com
Connection: close
Content-Length: 3
Content-Type: text/plain
EDIT 2:
The example code: https://github.com/Seeed-Studio/WiFi_Shield/blob/master/Examples/wifly_http/wifly_http.ino
is also throwing the same error.