Unexpected Error Google Apps Script Fetch - google-apps-script

I get an "Unexpected Error" from the following function:
function getBomgarFeedbackXML(){
var url = "https://help.tradingtechnologies.com/api/reporting.ns?" +
"username=xxxxxx&password=xxxxxx&generate_report=SupportCustExitSurvey&" +
"start_date=2000-01-01&duration=0&report_type=rep&id=all";
var response = UrlFetchApp.fetch(url).getContentText();
Logger.log(response);
return(Xml.parse(response, true));
}
The line that causes the error is:
var response = UrlFetchApp.fetch(url).getContentText();
I am able to fetch the URL programatically using other scripting languages, such as python
I have tried fetching the URL in my browser which I was able to do successfully
I can fetch "http://www.google.com" from Google apps script successfully
I get the following warning when navigating to the URL in chrome, could this be related to the issue ?
Any help is appreciated
Thanks

The last bit with the untrusted certs is the big clue here. Seems like the SSL cert associated with 'help.tradingtechnologies.com'is not valid or signed by a trusted CA per the Google Data Centers (from where the UrlFetch calls originate).
To work around this try this line of code instead of your UrlFetch call. Note the additional option for validateHttpsCertificates documented here.
var response = UrlFetchApp.fetch(url, {'validateHttpsCertificates':false}).getContentText();

Related

GAS Wialon Local Remote API: Retrieve login data

Good day,
I have a Wialon Local server (GPS monitoring system) and am planning to update a shared Google sheet using time-driven installable triggers.
As per the Wialon documentation, I am able to get the desired response when entering my API call in a browser.
However, in GAS, I am getting the below error when trying to retrieve data from the response.
API Call:
let apiURL = `http://my.tracking.site.come/wialon/ajax.html?svc=token/login&params={"token":"5dce19710a5e26ab8b7b898XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFCEED7DC03BC48FF5F8"}`
console.log(apiURL) // This URL works in a web browser as expected
var resText = UrlFetchApp.fetch(apiURL).getContentText() // error is raised on this line
console.log(resText)
The error:
11:48:27 AM Error
Exception: Invalid argument: http://my.tracking.site.come/wialon/ajax.html?svc=token/login&params={"token":"5dce19710a5e26ab8b7b898XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFCEED7DC03BC48FF5F8"}
wialonLogin # wialon.gs:20
Kindly advise what I am doing wrong here as I have very little experience with both GAS and Wialon Remote API ... will appreciate any assitance.
Thanks.
Solution is to encode the URL.
let apiURL = `http://my.tracking.site.come/wialon/ajax.html?svc=token/login&params={"token":"5dce19710a5e26ab8b7b898XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFCEED7DC03BC48FF5F8"}`
console.log(apiURL) // This URL works in a web browser as expected
var urlEncoded = encodeURI(apiURL);
var resText = UrlFetchApp.fetch(urlEncoded).getContentText() // error is raised on this line
console.log(resText)

Error when calling Drive.Files.get(fileId,{alt: 'media'}) in Google apps script (Google Drive API / REST V2)

I got an error when I try to get the content of a file (mimetype is "text/csv") stored in my Google drive using Drive.Files.get(fileId,{alt: 'media'}) from a Google apps script (I'm using Google Drive API / REST V2).
The strange thing is that the content of my file seems to be returned inside the message of the error, as follow:
{
"message":"Response Code: 200. Message: id\turl\tthumbnail_url\ttitle\tpublishedAt\tdescription\tchanelId\tcategoryId\ttags\tduration\tdislikeCount\tviewCount\tlikeCount\tcommentCount\r\n....",
"name":"HttpResponseException",
"fileName":"Code",
"lineNumber":142,
"stack":"\tat Code:142 (updateChannelVideos)\n",
"statusCode":200
}
Do you know how I can get the content of my file, from the server side, without using service like UrlFetchApp?
It appears that Google Apps Script can't handle a response from var myFile = Drive.Files.get(fileID,{alt: 'media'}); and if not already you might want to file as a bug.
Edit: updated related issue ticket here.
Instead of using the Drive Advanced Service you might find it easier to use DriveApp. Depending on the rest of your code no additional scopes would be required when mixing Drive and DriveApp calls.
For example you could use:
var myFile = DriveApp.getFileById(fileID).getAs('text/plain').getDataAsString();
I bypassed this issue using:
var fetchstring='https://www.googleapis.com/drive/v2/files/'+FILE_ID
fetchstring=fetchstring+'?mimeType=text/csv&alt=media';
var file_to_upload = UrlFetchApp.fetch(fetchstring, {
method: "GET",
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
}}).getBlob();
Adapat the mimetype / getBlob parts to your use case

Google Script - Conversion from text/html to application/pdf failed

I have a custom Google Script with a simple logic: it looks up parts from the spreadsheet and builds an in-memory HTML string, then I call the following code to produce the PDF.
var blob = Utilities.newBlob(html_body, 'text/html').getAs('application/pdf').setName(pdf_name);
var newDoc = DriveApp.createFile(blob);
var pdf_url = newDoc.getUrl();
Surprisingly for the same content, it sometimes works and randomly returns the error:
Conversion from text/html to application/pdf failed.
I see this happening most for larger files, so I am probably hitting some quota limitations.
But as per https://developers.google.com/apps-script/guides/services/quotas#current_limitations hitting any limitations should raise a relevant message.
Also documentation around https://developers.google.com/apps-script/reference/base/blob#getAs(String) does not state anything.
Any ideas?
Thank you!
I had the same problem, and did the following:
var html = HtmlService.createHtmlOutput(html_body);//This is now an object
html = html.getContent();//Get data as string - So its not an object or file
var blob = Utilities.newBlob(html,'application/pdf');//Create pdf from string
blob.setName(pdf_name);
In my case, the getAs('application/pdf') method was failing to convert a blob from a text file to a pdf file.
I had the same problem (that everybody else started getting Aug 9 2021) commencing Friday Aug 13th (because I run weekly processes/triggers).
Here is the WORKING solution by muhdtam...#gmail.com that I got from the Google Apps Script Community:
You have to add the following authorization to your "headers" section that is pointed to in your "options" statement that is part of...
var blob = UrlFetchApp.fetch(fileUrl, options).getBlob();
"authorization": "Bearer " + ScriptApp.getOAuthToken()
After I did that and re-tested, the error "Exception: Conversion from text/html to application/pdf failed" went away.
Google must have changed something but never told anybody.
I`m facing more or less the same trouble "text/html to application/pdf failed" error message.
As far as I understood, the issue is coming from the migration of the new version
"This project is running on our new Apps Script runtime powered by Chrome V8.", on existing script which was converting snapshot of only one tab from google sheet to PDF.
https://pastebin.pl/view/8ebb6742

Examine raw HTTP request from UrlFetchApp.fetch

I am working on something to interact with Amazon's REST API, but I keep getting an error in my response that points to a mal-formed request. I don't see any errors in the code (the parameter that it says is missing is clearly there), so I want to see the raw request that is being sent.
I don't see any available method that will let me do this. Maybe a server that will just include my request as its response?
Create your own endpoint that will echo to the screen your request. For example, to echo a GET request, send it to a script like this (that's been Publish > Deploy as web app):
function doGet(e) {
var test = 'Echo at ' + new Date() + '\n' + e.queryString;
return ContentService.createTextOutput(test);
}
A little late to the game (10 years) but you can now do this:
const requestResult = UrlFetchApp.getRequest(url, options);
Run it in debug mode and break after this executes to examine requestResult.
See: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#getrequesturl,-params for an official description and a full explanation of the properties for the options parameter.

google apps script UrlFetchApp.fetch limitations?

I have a simple script that pulls about 30,000 characters of JSON.
I get SyntaxError: Unexpected token: F (line 12) when I try to parse it with JSON.parse() or Utilities.jsonParse();
function refresh() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
sheet.clear();
var text = UrlFetchApp.fetch("http://blablah/json");
Logger.log(text.getContentText());
//error SyntaxError: Unexpected token: F (line 12)
json = JSON.parse(text);
)
The logger only shows about 59 lines of the JSON, but I was told that the logger has a space limit - but I'm not so sure that's it.
Running on my own server, JSON.parse parses the data just fine and so does jQuery get().
So I'm thinking UrlFetchApp.fetch() just can't get long files?
Hard to accept and I've found no documentation about it :(
You can check the UrlFetch and other services limitations on the new Apps Script dashboard. From my experience, Logger.log has a much more tighter limitation for a single log than UrlFetch, it's possible that UrlFetch is getting it fine, Logger.log is not showing it and you're running into other problem.
Try placing the getContentText result somewhere else, e.g. a spreadsheet cell. Or split it and call logger log in a for-loop.
A possible error that you might be facing (besides the quota limitation) is character encoding, getContentText has an optional parameter where you might inform the encoding of the page, have you checked that?