Skip to content

HTTPClient fails with https but WiFiClientSecure works #2783

Closed
@torntrousers

Description

@torntrousers

Trying to use HTTPClient to do an HTTP POST with TLS 1.2 fails but it works ok when using WiFiClientSecure.

This is with the latest github code as at 21st Dec 2016.

This sketch demostrates:

`
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "";
const char* password = "";

String urlHost = "quickstart.messaging.internetofthings.ibmcloud.com";
String urlPath = "/api/v0002/device/types/typeId/devices/myDevice1/events/eventId";
int urlPort = 8883; // or 1883 for non-secure

void setup() {
Serial.begin(115200); Serial.println();
initWifi();
}

void loop() {
doPost1();
doPost2();
delay(10000);
}

void doPost1() {
Serial.println("*** HTTPClient ***");
HTTPClient http;
String url = (urlPort == 8883 ? "https://" : "http://") + urlHost + ":" + urlPort + urlPath;
Serial.println(url);
String payload = String("{ "d": {"aMessage": "") + millis()/1000 + ""} }";
Serial.print("POST payload: "); Serial.println(payload);
http.begin(url, payload);
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(payload);
Serial.print("HTTP POST Response: "); Serial.println(httpCode);
}

void doPost2() {
Serial.println("*** WiFiClientSecure ***");
WiFiClientSecure client;

Serial.print("connect: "); Serial.println(urlHost);
while (!client.connect(urlHost.c_str(), 8883)) {
Serial.print(".");
}
Serial.println("Connected");

String postData = String("{ "d": {"aMessage": "") + millis()/1000 + ""} }";

String msg = "POST " + urlPath + " HTTP/1.1\r\n"
"Host: " + urlHost + "\r\n"
"Content-Type: application/json\r\n"
"Content-Length: " + postData.length() + "\r\n"
"\r\n" + postData;

client.print(msg);
Serial.print(msg);

Serial.print("\n*** Request sent, receiving response...");
while (!!!client.available()) {
delay(50);
Serial.print(".");
}
Serial.println();
Serial.println("Got response");

// Read all the lines of the reply from server and print them to Serial
while(client.available()){
Serial.write(client.read());
}

Serial.println();
Serial.println("closing connection");
client.stop();
}

void initWifi() {
Serial.print("Connecting to: "); Serial.print(WiFi.SSID());
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
`

Metadata

Metadata

Assignees

No one assigned

    Labels

    waiting for feedbackWaiting on additional info. If it's not received, the issue may be closed.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions