我对HTTP的函数GET函数有一点问题。程序读取ID号,输入(新行)后,它应该从REST API获取数据。问题是我必须按两次输入API来获取数据。这是代码
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0x90, 0x02, 0xBA, 0xEF, 0xCA, 0x33 };
char server[] = "xxx.xx";
EthernetClient client;
char tmp;
char buffer[30];
int bufferCounter = 0;
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
}
delay(1000);
Serial.println("Ready");
}
void getData(char* num ){
Serial.println("connecting...");
if (client.connect(server, 80)) {
Serial.println("connected");
client.print("GET /api/id/");
client.print(num);
client.println("/?format=json HTTP/1.1");
client.println("Host: xxx.xx");
client.println("Authorization: Token xxxxxxxxxxxxxxxxxxxxx");
client.println("Connection: close");
client.println();
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
while (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
}
void loop() {
if (Serial.available() > 0) {
tmp = Serial.read();
if(tmp == '\n'){
buffer[bufferCounter] = 0;
bufferCounter = 0;
Serial.println(buffer);
getData(buffer);
}
else{
buffer[bufferCounter] = tmp;
bufferCounter++;
}
}
}
在串行链接上,我收到此消息。起初
Ready
当我在那里写35并按回车时我得到了这个
35
connecting...
connected
然后我必须再次按回车键,最后我得到正确的数据,但连接失败,我不知道为什么
connecting...
connection failed
HTTP/1.1 404 NOT FOUND
Date: Tue, 22 Nov 2016 16:18:18 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Vary: Accept, Cookie
18
{"detail":"not found."}
0
disconnecting.
有人可以帮我,问题出在哪里?谢谢。