esp8266拉取天气API时无法完全读取API内容如何解决? 10C

问题:在使用esp8266获取实时天气状况时没有问题,但是在获取未来一天的天气状况时出现了获取的信息不完全,我尝试改变了HTTP消息获取长度最大值但是没有效果,在串口监视器看到的信息不完全,但是在浏览器中测试同样的请求api是可以获得完整的消息的。

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <Wire.h>


const char* ssid     = "";         
const char* password = "";        
const char* host = "api.seniverse.com";
const char* APIKEY = "";  
const char* city = "tianjin";     
const char* language = "en";//zh-Hans 简体中文


const unsigned long BAUD_RATE = 115200;                   
const unsigned long HTTP_TIMEOUT = 5000;               
const size_t MAX_CONTENT_SIZE = 5000;                  





WiFiClient client;
char response[MAX_CONTENT_SIZE];
char endOfHeaders[] = "\r\n\r\n";


void setup() {
  WiFi.mode(WIFI_STA);     //设置esp8266 工作模式
  Serial.begin(BAUD_RATE);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);   //连接wifi
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  delay(100);
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());   //返回8266获得的ip地址
  client.setTimeout(HTTP_TIMEOUT);


}


void loop() {

  while (!client.connected()){
     if (!client.connect(host, 80)){
         Serial.println("connection....");
         delay(100);
     }
  }
  if (sendRequest(host, city, APIKEY) && skipResponseHeaders()) {
    clrEsp8266ResponseBuffer();
    readReponseContent(response, sizeof(response));
  }
  delay(5000);
}


bool sendRequest(const char* host, const char* city, const char* APIKEY) {
  String GetUrl = "/v3/weather/daily.json?key=";
  GetUrl += APIKEY;
  GetUrl += "&location=";
  GetUrl += city;
  GetUrl += "&language=";
  GetUrl += language;
  GetUrl += "&start=0&days=2";

  client.print(String("GET ") + GetUrl + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  Serial.println("create a request:");
  Serial.println(String("GET ") + GetUrl + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n");
  delay(1000);
  return true;
}


bool skipResponseHeaders() {
  bool ok = client.find(endOfHeaders);
  if (!ok) {
    Serial.println("No response or invalid response!");
  }
  return ok;
}

void clrEsp8266ResponseBuffer(void){
    memset(response, 0, MAX_CONTENT_SIZE);      //清空
}


void readReponseContent(char* content, size_t maxSize) {
  Serial.println(*content);
  size_t length = client.peekBytes(content, maxSize);
  delay(100);
  Serial.println("Get the data from Internet!");
  content[length] = 0; 
  Serial.println(content);
  Serial.println("Read data Over!");

  client.flush();
  delay(2000);
}

图片说明

1个回答

Solozxy
Solozxy 多谢,但是我这个程序存不到完整api内容的原因是什么呢
9 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!