如何使用WiFly从Arduino Uno R3获取GET请求?

时间:2015-02-06 04:48:52

标签: api arduino

我环顾四周,找不到任何类似于我想做的事情。

背景:我正试图通过WiFly盾牌将这个名为http://api.football-data.org的API的足球信息传输到我的Arduino上。现在这里是我提出的一些代码以某种方式获取此信息。但是,此代码尚不可用。

#include <SPI.h>
#include "WiFly.h" //include the WiFly experimental library

char server[] = "api.football-data.org";
WiFlyClient client(server, 80);

void setup(){

  Serial.begin(9600);
  Serial.println("Serial Begun :D");
  WiFly.begin();
  Serial.println("WiFly Begun :D");

  Serial.print("IP: ");
  Serial.println(WiFly.ip()); //print out WiFly IP

}

void loop(){

  if(client){
    while(client.connected()){
      if(client.available()){
        char c = client.read();
        delay(10);
        Serial.print(c);

        if(c == '\n'){
          Serial.println("connected");
          client.print("GET http://api.football-data.org/alpha/soccerseasons/357/leagueTable");
          Serial.print("GET http://api.football-data.org/alpha/soccerseasons/357/leagueTable");
          client.println(" HTTP/1.1");
          Serial.println(" HTTP/1.1");
          client.println("Host: api.football-data.org");
          Serial.println("Host: api.football-data.org");
          client.println("X-Auth-Token: (My Token here)");
          Serial.println("X-Auth-Token: (My Token here)");  
          client.println("Connection: close");
          Serial.println("Connection: close");
          client.println();
        }

      }
    }
    delay(100);
    client.flush();
    client.stop();
  }
}

我应该做些什么更改才能从api.football-data.org服务器获得正确的HTTP响应?

1 个答案:

答案 0 :(得分:0)

我根据我在WiFly库中找到的一些示例,特别是WiFly_WebClient示例,让它工作。那里非常实用。这是功能齐全的代码:

#include <SPI.h>
#include "WiFly.h" //include the WiFly experimental library
#include "Credentials.h"


WiFlyClient client("api.football-data.org", 80);

void setup(){

  Serial.begin(9600);
  Serial.println("Serial Begun :D");
  WiFly.begin();

  if (!WiFly.join(ssid, passphrase)) {
    Serial.println("Association failed.");
    while (1) {
      // Hang on failure.
    }
  } 

  Serial.print("connecting to server...");
  if(client.connect()){
    Serial.println("connected");
    client.print("GET http://api.football-data.org/alpha/soccerseasons/357/leagueTable");
    Serial.print("GET http://api.football-data.org/alpha/soccerseasons/357/leagueTable");
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: api.football-data.org");
    Serial.println("Host: api.football-data.org");
    client.println("X-Auth-Token: My Token");
    Serial.println("X-Auth-Token: My Token");  
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
  } else{
    Serial.println("connection failed");
  }


}

void loop(){

  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}