LoginSignup
20
15

More than 3 years have passed since last update.

GASからJSONでPOST(BASIC認証)する方法

Last updated at Posted at 2018-05-30

GASでPOST(BASIC認証)する

curl -X POST -H "Content-Type: application/json" -d @lead.json --user "user:password" https://post-url.com

このcURLと同じことをGASで実現したかった

function sendPost(){
    const auth_data = Utilities.base64Encode(`${USER}:${PASSWORD}`);

    /* POSTするBODYを設定 */
    const data = {
        "A": "AAA",
        "B": "BBB"
    };

    /* POSTするためのOPTIONを設定 */
    const options = {
        "method": "post",
        "contentType": "application/json",
        "payload": JSON.stringify(data),
        "headers": {"Authorization" : `Basic ${auth_data}`},
        "muteHttpExceptions": true
    };
    const response = UrlFetchApp.fetch('https://post-url.com', options);
    Logger.log(response.getContentText());
}

意外と簡単だった。

POSTの実行自体はUrlFetchApp.fetchでできる。
headersにBasic認証用にAuthorizationを設定する。
Utilities.base64Encodeが標準で用意されているので、簡単にBasic認証できる。
muteHttpExceptionsをtrueにしておけば、Exceptionが発生したときにresponseに内容を返してくれるので、ログを見れば、オールオッケー

20
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
15