This tutorial is a step-by-step explanation of how to use Google App Script to send HTTP GET and POST.
In order to send an request with App Scripts, you’ll need to use the UrlFetchApp library.
The UrlFetchApp.fetch() function requires two parameters. The first parameter is the URL of the request. The second parameter is an options object with the request method and any parameters or data needed to send the request. For example, to send an HTTP request, you can use something like below:
Table
1. App script – Send HTTP POST request
- send with a JSON payload
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const data = { 'name': 'Max', 'age': 18 };; const options = { "method": "post", "headers": { "Authorization": "Basic token") }, "contentType": "application/json", "payload" : JSON.stringify(data) }; UrlFetchApp.fetch('https://httpbin.org/post', options); |
- send with form data
1 2 3 4 5 6 7 8 9 |
const formData = { 'name': 'Max', 'age': '18' }; const options = { 'method' : 'post', 'payload' : formData }; UrlFetchApp.fetch('https://httpbin.org/post', options); |
2. App script – Send HTTP GET request
1 2 |
const response = UrlFetchApp.fetch('http://www.google.com/'); Logger.log(response.getContentText()); |
Q: Can I adjust the User agent in App script GET request?
A: unfortunately, the answer is no, you can try below script and see the User-agent still remain at “Google-Apps-Script”.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function checkForUserAgent() { const url = "https://httpbin.org/get" const params = { headers: { 'Content-Type': "application/json", 'Accept': "application/json", 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}, muteHttpExceptions: true, method: "GET", contentType: "application/json", validateHttpsCertificates: false, }; const response = UrlFetchApp.fetch(url, params); Logger.log(response.getContentText()); } |
Thanks for your reading. I hope this article will help you better understand google app script.