How to open a URL with Spark Core?

OK I tested this and it work for me. Maybe you should look at your server?

char server[] = "www.google.com";
char url[] = "search?q=unicorn";

TCPClient client;

void setup() {
    Serial.begin(9600);

}

void loop() {
    
    Serial.println("Starting request");
    int retval = getrequest();
    Serial.print("Returns ");
    Serial.println(retval);
    delay(10000);
}

int getrequest(){
client.connect(server, 80);

if (client.connected()) {
        Serial.println("Connected to server.");
        client.print("GET ");
        client.print(url);
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(server);
        client.println("Connection: close");
        client.println();

        unsigned int count = 0;
        unsigned long lastTime = millis();
        while( client.available()==0 && millis()-lastTime<10000) { //ten second timeout
          }  //do nothing
        lastTime = millis();
        while( client.available() && millis()-lastTime<10000 ) {  //ten seconds
          client.read();  //flush data
          count++;
        }
        client.flush();  //for safety

        //client.flush();
        delay(400);
        client.stop();
        Serial.print("sent and closed-bytes: ");
        Serial.println(count);
    return 1;
     }
    else {
        client.flush();
        client.stop();
        Serial.println("Not connected");
        return 0;
    }
}
1 Like