2016-09-26 2 views
0

Arduino IDE로 프로그래밍 된 ESP8266 ESP-01 WiFi 모듈에서 URL에 GET 요청을 보내고 내용을 읽으려고합니다.
ESP8266WiFi 라이브러리를 사용하는 아래 코드를 수정하려고 할 때 호스트 대신 무엇을 대체해야하는지 명확하지 않습니다. 호스트 또는 다른 URL에 URL을 입력해야합니까? 줄을 편집하는 방법도 있습니다.esp8266WiFi 라이브러리 사용 방법 웹 사이트에서 정보 얻기 GET 요청

client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
      "Host: " + host + "\r\n" + 
      "Connection: close\r\n\r\n"); 
#include <ESP8266WiFi.h> 

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

const char* host = "data.sparkfun.com"; 
const char* streamId = "...................."; 
const char* privateKey = "...................."; 

void setup() { 
    Serial.begin(115200); 
    delay(10); 

    // We start by connecting to a WiFi network 

    Serial.println(); 
    Serial.println(); 
    Serial.print("Connecting to "); 
    Serial.println(ssid); 

    WiFi.begin(ssid, password); 

    while (WiFi.status() != WL_CONNECTED) { 
    delay(500); 
    Serial.print("."); 
    } 

    Serial.println(""); 
    Serial.println("WiFi connected"); 
    Serial.println("IP address: "); 
    Serial.println(WiFi.localIP()); 
} 

int value = 0; 

void loop() { 
    delay(5000); 
    ++value; 

    Serial.print("connecting to "); 
    Serial.println(host); 

    // Use WiFiClient class to create TCP connections 
    WiFiClient client; 
    const int httpPort = 80; 
    if (!client.connect(host, httpPort)) { 
    Serial.println("connection failed"); 
    return; 
    } 

    // We now create a URI for the request 
    String url = "/input/"; 
    url += streamId; 
    url += "?private_key="; 
    url += privateKey; 
    url += "&value="; 
    url += value; 

    Serial.print("Requesting URL: "); 
    Serial.println(url); 

    // This will send the request to the server 
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
       "Host: " + host + "\r\n" + 
       "Connection: close\r\n\r\n"); 
    unsigned long timeout = millis(); 
    while (client.available() == 0) { 
    if (millis() - timeout > 5000) { 
     Serial.println(">>> Client Timeout !"); 
     client.stop(); 
     return; 
    } 
    } 

    // Read all the lines of the reply from server and print them to Serial 
    while(client.available()){ 
    String line = client.readStringUntil('\r'); 
    Serial.print(line); 
    } 

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

답변

1

귀하의 라인 client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");은 OK입니다. 변경하지 않아도됩니다.

host의 경우 도메인 이름 또는 IP 주소를 입력해야합니다. 예 : const char* host = "example.com";. 당신이 http://stackoverflow.com/questions/39707504/how-to-use-esp8266wifi-library-get-request-to-obtain-info-from-a-website을 얻고 싶은 경우에

당신이 있어야합니다

const char* host = "stackoverflow.com"; 
String url = "https://stackoverflow.com/questions/39707504/how-to-use-esp8266wifi-library-get-request-to-obtain-info-from-a-website"; 
관련 문제