Arduino 分析 Get 字串

說明

這裡主要目的是取得 Get 請求後面的

使用者帳號及密碼

而這裡是針對 ESP8266 模組的 Client 的請求資料進行分析

當表單提交時可以在 Arduino 的監控台看到

Client 的請求資料 如下

+IPD,1,370:GET /?username=king&password=joihoih HTTP/1.1

因此這裡要做如何得到 username 後面的帳號

以及 password 後面的密碼

核心程式碼

indexOf 可以取得欲搜尋字串的第一個位置

這裡以取得 username 為例

Step 1 取得 username 位置

String text = "+IPD,1,370:GET /?username=king&password=joihoih HTTP/1.1";
int getNameIndex = text.indexOf("username");
Serial.print("username location = ");
Serial.println(getNameIndex);

輸出結果 username location = 17

Step 2 取得 & 位置

String text = "+IPD,1,370:GET /?username=king&password=joihoih HTTP/1.1";
int getAndIndex = text.indexOf("&");
Serial.print("& location = ");
Serial.println(getAndIndex);

輸出結果 & location = 30

Step 3 擷取 king

透過 Step 1 和 Step 2 的位置可以取得 username=king

但這裡我們只需要 king的部分

因此要扣掉 username= 的長度只取 king 字串的部分

因此在寫迴圈的時候條件的部分要 -9

儲存字串的部分要 +9

這部分可以透過底下的副程式 GetAccountInfo 看到

完整程式碼

void setup() 
{
  Serial.begin(9600);
  String text = "+IPD,1,370:GET /?username=king&password=joihoih HTTP/1.1";

  int getNameIndex = text.indexOf("username");
  int getAndIndex = text.indexOf("&");
  int getPassWordIndex = text.indexOf("password");
  int getSpace = text.indexOf("HTTP/1.1") - 1;
 
  Serial.print("username location = ");
  Serial.println(getNameIndex);
  Serial.print("& location = ");
  Serial.println(getAndIndex);
  Serial.print("password location = ");
  Serial.println(getPassWordIndex);

  Serial.print("username = ");
  Serial.println(GetAccountInfo(text,getNameIndex,getAndIndex));
  Serial.print("PassWord = ");
  Serial.println(GetAccountInfo(text,getPassWordIndex,getSpace));
}

void loop()
{

}

String GetAccountInfo(String FullText,int PreIndex,int LastIndex){

  String AccountInfo = "";

  for (size_t i = 0; i < LastIndex - PreIndex - 9; i++)
  {
    int count = PreIndex + i;
    AccountInfo += FullText[count+9];
  }
  
  return AccountInfo;
}

輸出結果

username location = 17
& location = 30
password location = 31
username = king
PassWord = joihoih
Last modification:April 21st, 2020 at 05:20 pm