如何使用ESP8266 Arduino框架从REST API接收JSON响应

时间:2019-02-22 05:48:13

标签: arduino microcontroller arduino-esp8266

我正在尝试使用Beyond Verbal RST API通过ESP8266的HTTP post方法发布语音示例数据。 API通信的第一步是使用POST方法获取访问令牌。您可以检查以下代码。使用此代码,我只是在串行输出上收到“无法发布”响应。

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "xxxxxx";
const char *pass = "xxxxxx";
String token;

HTTPClient https;
WiFiClientSecure client;
String getRecordID(String stoken);

void setup() {

Serial.begin(115200);
Serial.println("connecting to network..");
WiFi.begin(ssid, pass);

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



void loop() {

String ret;
token = getAccessToken();
delay(2000);
Serial.println(token);
}




String getAccessToken(){
//    client.setInsecure();
  const char * host = "token.beyondverbal.com";
  const uint16_t port = 443;
  const char * path = "/token";

  StaticJsonBuffer<1000> jb;
  String res;
  Serial.println("conntecting to server..");

  if (https.begin(client, host, port, path)) {
    https.addHeader("Content-Type", "x-www-formurlencoded");
    int httpsCode = https.POST("grant_type=client_credentials&apiKey=1d0956a4-3deb-431a-b3e0-45f5c371fe99");
        if (httpsCode > 0) {
              if (httpsCode == HTTP_CODE_OK) {
                JsonObject& obj = jb.parseObject(https.getString());
                String token = obj["access_token"];
                if (obj.success()) {
                   res =  token;
                } else {
                    res = "failed to parse json";
                }                
              }
        } else {
            res = "failed to Post";
        }
   } else {
    res = "failed to connect to server";
   } 
https.end();
return res;
}

查看指南文档,请阅读认证部分。我已经按照步骤进行了尝试,并尝试了几种方法,但还是没有运气。

但是我的API代码和其他参数都可以。我已经尝试过Mozilla Firefox插件和其他平台的API发布方法。我从任何地方都能成功获得令牌。但是我仍然无法通过我的代码获得令牌。

请为我检查有关此问题的解决方案。

1 个答案:

答案 0 :(得分:0)

使用这些库。 ESPAsyncTCPasyncHTTPrequest

然后使用下面的代码。样本代码。

#include <ESPAsyncTCP.h>
#include <asyncHTTPrequest.h>

asyncHTTPrequest client;
asyncHTTPrequest client2;

void onClientStateChange(void * arguments, asyncHTTPrequest * aReq, int readyState) {
  Serial.println(readyState);
  switch (readyState) {
    case 0:
      // readyStateUnsent     // Client created, open not yet called
      break;

    case 1:
      // readyStateOpened     // open() has been called, connected
      break;

    case 2:
      // readyStateHdrsRecvd  // send() called, response headers available
      break;

    case 3:
      // readyStateLoading    // receiving, partial data available
      break;

    case 4:
      // readyStateDone       // Request complete, all data available.
#ifdef SERIAL_DEBUG
      Serial.println(aReq->responseHTTPcode());
#endif
      if (aReq->responseHTTPcode() != 200) {
#ifdef SERIAL_DEBUG
        Serial.println("return");
#endif
        return;
      }
      String response = aReq->responseText();
#ifdef SERIAL_DEBUG
      Serial.println(response.c_str());
#endif
      break;
  }
}

void setupClient() {
  String URL = "dummy.restapiexample.com/api/v1/create";

  client.setTimeout(5);
  client.setDebug(false);
  client.onReadyStateChange(onClientStateChange);

  client.open("POST", URL.c_str());
  client.setReqHeader("Content-Type", "application/json");
  client.send("{\"name\":\"test\",\"salary\":\"123\",\"age\":\"23\"}");

  String URL2 = "jsonplaceholder.typicode.com/users";

  client2.setTimeout(5);
  client2.setDebug(false);
  client2.onReadyStateChange(onClientStateChange);

  client2.open("GET", URL2.c_str());
  client2.send();
}

始终与异步客户端连接,因为它不会阻塞您的主要执行,直到您获得响应为止。