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

问题描述 投票:1回答:1

我正在尝试使用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 post方法。从各地我成功获得了令牌。但是我仍然无法使用我的代码获取令牌。

请检查我的问题解决方案。

arduino microcontroller arduino-esp8266
1个回答
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();
}

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

© www.soinside.com 2019 - 2024. All rights reserved.