Simple post request to a server

I am trying to make a simple POST request over TCP client when you press switch button and I tried first to use test server but it just doesn’t send a request through. I tried with webhook and it worked but I can’t use webhook because at the end I will need to send requests to local host server from .NET application. So can anyone suggest me what should I do or change in code please?

This is my test code:

int switch1 = A0;

TCPClient client;

const char serverURL[] = "http://requestb.in/14159jw1";
const int serverPort = 80;

void setup() {
pinMode(switch1,INPUT);

}

void loop() {
    if(digitalRead(switch1) == HIGH){
        
        String command = "on";
        
        if(client.connect(serverURL, serverPort)){;
        client.println("POST /14159jw1 HTTP/1.1");
        client.println("HOST: http://requestb.in")
        client.print("Content-Length: ");
        client.println(command.length());
        client.println("Content-Type: ");
        client.println();  
        client.println(command);
        }
        
    }
    
}

This worked for me. The client.connect method takes a hostname, not a URL. And I made a few other minor changes:

int switch1 = A0;

TCPClient client;

const char serverHost[] = "requestb.in";
const int serverPort = 80;
const unsigned long MAX_SEND_FREQUENCY_MS = 5000;

unsigned long lastSent = 0;

void setup() {
	pinMode(switch1,INPUT);
}

void loop() {
	if(digitalRead(switch1) == HIGH && millis() - lastSent > MAX_SEND_FREQUENCY_MS){
		lastSent = millis();

		String command = "on";

		if(client.connect(serverHost, serverPort)){;
			client.println("POST /17dz92b1 HTTP/1.1");
			client.println("Host: requestb.in");
			client.printlnf("Content-Length: %d", command.length());
			client.println("Content-Type: text/plain");
			client.println();
			client.println(command);
			client.flush();
		}

	}
}

3 Likes

Thank you for your quick response and it does work also. But know I have to use this inside of a bigger program and I need to connect to local host server which is runned by .NET application, which is reacting to POSTs from Photon.
I have IP adress and Port number of server and when I change serverHost to IP and Port it doesn’t send a request to server. Do you have any idea what could be wrong? Thanks again for your help.

I believe you need to use an IPAddress, not a String, when using an IP address with connect(). You’ll frequently see something like this as a global variable in the code. You just pass server instead of serverHost to the connect method.

IPAddress server(192,168,1,10);
2 Likes

Thank you very much for taking your time and helping me, everything is working as expected. :smiley:

1 Like