我正在尝试将XML数据用于天气服务,我正在使用具有方便的xml和API系统的开放天气地图。但是,在使用我的代码时,我似乎没有得到任何回应。我使用了WebClient演示代码,这似乎可以工作并将响应打印到串行控制台。但是,在使用我的代码时,我没有收到回复。
当我使用下面的代码时,我得到串行响应"连接到XML数据。"但是当程序进入循环时,我没有得到"读取HTML数据",而是得到"断开连接"。有人可以建议我如何更改代码? (串行控制台输出位于主代码下方。)
#include <SPI.h>
#include <Ethernet.h>
int cityID = 2644487;
char APIkey[33] = "SOME API KEY"; //32 length
byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02};
IPAddress ip(192, 168, 1, 89);
byte gateway[] = {192, 168, 1, 254};
byte subnet[] = {255, 255, 255, 0};
//byte dns[] = {81, 139, 57, 100};
//Open weather map xml
char server[] = "http://api.openweathermap.org";
int port = 80; //usually 80 for http.
EthernetClient client;
int temperature = 0;
char buff[80];
byte pos = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);//used to disable the SD Card
Serial.begin(9600);
Serial.println("Initialising...");
// Start Ethernet
//Ethernet.begin(mac, ip, dns, gateway, subnet);
if (!Ethernet.begin(mac)) { //if DHCP does not automatically connect
Serial.println("Using gateway and subnet");
Ethernet.begin(mac, ip, dns, gateway, subnet);
}
else {
Serial.println("Using mac and ip");
}
delay(1000); // delay to give the ethernet shield a second to connect.
Serial.println("");
Serial.print("Connecting to OWM server using cityID: ");
Serial.println(cityID);
Serial.print("Using API key: ");
Serial.println(APIkey);
if (client.connect(server, port))
{
Serial.println("Connected to XML data.");
client.print("GET /data/2.5/weather?id=2644487&appid=SOME API KEY&mode=xml&units=metric HTTP/1.1\r\n");
client.print("HOST: http://api.openweathermap.org\r\n");
client.print("Connection: Close\r\n");
client.print("\r\n");
}
else
{
Serial.println("Failed to connect.");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
Serial.println("Reading HTML data");
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("Disconnecting.");
client.stop();
// do nothing forevermore:
while (true);
}
}
串行控制台输出
Initialising...
Using mac and ip
Connecting to OWM server using cityID: 23047
Using API key: SOME API KEY
Connected to XML data.
Disconnecting.