Connecting to a web Page

Try this, i cant actually get it to work with my slow connection at the moment but that’s nothing unusual. @bko could you give it a quick try too, I’ve been trying it for 3 hrs now and still nothing will connect for me… its a couple of your test/example codes combined :slight_smile:

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

TCPClient client;

void setup() {
    Serial.begin(9600);
    while (!Serial.available()) SPARK_WLAN_Loop();
    
    IPAddress dnshost(ip_config.aucDNSServer[3], ip_config.aucDNSServer[2], 
                  ip_config.aucDNSServer[1], ip_config.aucDNSServer[0]);


    Serial.print("SSID: ");
    Serial.println(WiFi.SSID());
    Serial.print("Core IP: ");
    Serial.println(WiFi.localIP());
    Serial.print("Gateway: ");
    Serial.println(WiFi.gatewayIP());
    Serial.print("Mask: ");
    Serial.println(WiFi.subnetMask());
    Serial.print("DNS host: ");
    Serial.println(dnshost);        // DNS host
    Serial.print("WiFi RSSI: ");
    Serial.println(WiFi.RSSI());
    
}

void loop() {
    
    Serial.println("Starting request");
    uint32_t ip_addr = 0;
    unsigned long tic = millis();
    Serial.print("Looking up IP for: ");
    Serial.println(hostname);
    int16_t retval = gethostbyname((char*)hostname, strlen(hostname), &ip_addr);
    unsigned long toc = millis();
    IPAddress resolvedIP(BYTE_N(ip_addr, 3), BYTE_N(ip_addr, 2), BYTE_N(ip_addr, 1), BYTE_N(ip_addr, 0));
    Serial.print("The IP is: ");
    Serial.print(resolvedIP);
    Serial.print(" Return Code: ");
    Serial.println(retval);
    Serial.print("Time taken: ");
    Serial.println(toc-tic);
    Serial.print("Connecting to server.");
    tic = millis();
    
    if (client.connect(hostname, 80)) {
        Serial.print(" Connected OK");
        client.print("GET ");
        client.print(url);
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(hostname);
        client.println("Connection: close");
        client.println();
        // client.println(); //sometimes another print line is required on some servers.
        Serial.println(" Sent GET request, Awaiting resopnse");

        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
          Serial.print(client.read());  //flush data
          count++;
        }
        client.flush();  //for safety

        //client.flush();
        delay(400);
        client.stop();
        Serial.println();
        Serial.print("Done, Total bytes: ");
        Serial.println(count);
    
     }
    else {
        client.flush();
        client.stop();
        Serial.println("Could not connect");
    }

    delay(10000);
}
1 Like