JSONProxy At http://jsonp.afeld.me/ Error - json

I am using the following function to get JSON data particular API via JSONP Proxy mentioned above. I want to get the MESSAGE from this API.
function callMe() {
var part1 = 'https://jsonp.afeld.me/?callback=?&url=';
var part2 = 'http://m.icta.lk/services/railwayservicev2/station/getByID?id=168';
var url = part1 + part2;
$.getJSON(url, function(data) {
document.getElementById("stName").innerHTML = data.MESSAGE;
});
}
For the above URL I'm getting a message saying Found 1 Results!. That's OK. Proxy is working fine.
But when this URL is assigned to part2 variable
part2 = http://m.icta.lk/services/railwayservicev2/ticket/getPrice?startStationID=184&endStationID=61&lang=en
I'm getting a message saying Missing Parameters.
Nothing is wrong with above two URLs. You can check. This works well for the first one, But not for the second one. Please help

Since your part2 contains query parameters, the JSONP server doesn't know that you're trying to pass the startStationID= to it, or through to the other API. The solution here is to encode your part2:
var url = part1 + encodeURIComponent(part2);
which turns all the ampersands (&) in part2 to %26.

Related

Access Specific Google Trend using Google Apps Script

I am trying to write a script to access the specific values that are displayed in the following line graph:
Ideally, I want to get the last value (43) from the line graph. For that I tried to run the following sample code:
function W5(){
var url ='https://trends.google.com/trends/explore?geo=US&q=%2Fm%2F07s_c';
var result = UrlFetchApp.fetch(url);
const $ = Cheerio.load(result.getContentText());
Logger.log($);
return;
}
But it is giving me the following error message, due to which I am unable to parse any data and process it. It's strange because I have not made a single successful request even once but message says too many requests:
Exception: Request failed for https://trends.google.com returned code
429. Truncated server response: Error 429 (Too Many Req...
(use muteHttpExceptions option to examine full response)
I followed this solution by changing the parameters according to my requirement:
function startQuery() {
var sheet = ss.getSheetByName("Sheet2");
// start the query
var result = buildQueryString(sheet.getRange("A2").getValue(),
sheet.getRange("B2").getValue());
// display the resulting link in a cell
sheet.getRange("C2").setValue(result);
var csv_result = generateCsvDownload(sheet.getRange("A2").getValue(),
sheet.getRange("B2").getValue());
sheet.getRange("D2").setValue(csv_result);
}
function buildQueryString(geo,q) {
return "http://www.google.com/trends/explore?" +
"geo=" + encodeURIComponent(geo) +
"&q=" + encodeURIComponent(q)
}
function generateCsvDownload(geo,q) {
return "http://www.google.com/trends/viz?" +
"geo=" + encodeURIComponent(geo) +
"&q=" + encodeURIComponent(q) +
"&graph=all_csv";
}
This script takes parameters from the sheet table (starting from Column A):
geo
q
Query_Result
CSV_Download_Link
csv_result
US
uneployement
But it just creates a link instead of actual CSV data output. Any help with that would be much appreciated. Thank you

Delay in between two calls (POST and GET) in Google Apps script

My first request on StackOverflow! I really hope you can help me!
I want to create a process to automatize a data report from a system to a sheet; I thought I could use their API, apps script, and export the data on google sheets.
To do so, I need to run two calls on the API:
A POST call, which runs the report within the system (it requires a date range as body).
In return, I will get an ID that is associated with the data generated and it expires after some time.
A GET call, which is a URL that contains the ID generated in the first call and created with a concatenation.
The first call works fine; I get in return the ID successfully.
My problem is when I run the second call, I don’t get any data in return, and I don’t understand what’s the issue, I can see the URL is concatenated correctly because if I copy the URL from the log and I test it on another apps script or on Postman, it works perfectly fine!
Could someone help me in case I am doing something wrong?
Here’s the code:
function callEvents() {
var API_KEY = "xxx";
var data = { 'Start Date': '2021-05-03', 'End Date': '2021-06-03' }
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data) };
//This is the first call
var urlEncoded = encodeURI('https://website/api/dataviewresult/
etc/json/?api_key=' + API_KEY);
var url = UrlFetchApp.fetch(urlEncoded, options);
var result = JSON.parse(url.getContentText());
Logger.log(url.getContentText());
//here I retrieve the ID to use in the second call
var ipdataview = (result["contents"]["id"]);
Logger.log(ipdataview);
//here is the concatenation and the second call
var urlEncoded2 = encodeURI('https://website/api/dataviewresult/etc/json/'+ipdataview+'/?api_key=' + API_KEY);
Logger.log(urlEncoded2);
var response = UrlFetchApp.fetch(urlEncoded2);
Logger.log(response.getContentText());
I found out the solution, I was doing the second call (Get) too soon from the first one, so the data was not being picked up.
I used utilities.sleep() for about 2 seconds and it worked perfectly.
Thank you for everyone helping!
S

Is there a way to modify json received callback?

I'm receiving a callback from a server in my Google app script via doPost.
The problem is, my Json format is with a this word in front of the Json "Data=", because of that I'm not able to work with the Json callback.
The code:
Function doPost(e){
var r = e.postdata.contents
Logger.log(r)
}
I'm receiving the bellow format.
data={""retorno"":{""estoques"":[{""estoque"":{""codigo"":""001a"",""nome"":""M\u00e1scara 100% Algod\u00e3o Lav\u00e1vel Dupla Prote\u00e7\u00e3o - 10 Unidades"",""estoqueAtual"":50,""depositos"":[{""deposito"":{""id"":7939278964,""nome"":""Geral"",""saldo"":""50.0000000000"",""desconsiderar"":""N"",""saldoVirtual"":""50.0000000000""}}]}}]}}
Anyway to remove this "Data="?
Thanks
If you just want to remove the substring data= - the easiest would be to use the method silce()
Sample:
var r = e.postdata.contents;
var sliced = r.toString().slice(5);
Logger.log(slide);

Find googleusercontent.com URL for an InlineImage

Whenever I upload an image (i.e. InlineImage) in a Google Doc, it uploads it to a CDN and references a googleusercontent.com URL. If I'm using Google Apps Script on a DocumentApp, I can get an instance of InlineImage. I know I can convert it to a base64 and then create a data URL for this image. However, instead of creating this gigantic URL, I'd rather just use the existing googleusercontent.com URL.
How do I find out the googleusercontent.com URL for an InlineImage?
Essentially you need to do the following:
Set a unique alt description on the InlineImage.
Get the HTML of the entire document.
Use a regex to find the <img tag using the unique alt description from step 1.
function getUrlOfInlineImage(inlineImage) {
var altDescription = inlineImage.getAltDescription(); // warning: assumes that the alt description is a uuid. If it's not unique, this function might return a different image's url. If it's not a UUID, it might contain illegal regex characters and crash.
if (!altDescription) {
inlineImage.setAltDescription(Utilities.getUuid());
// TODO: We currently crash because if we attempt to get the HTML right after calling setAltDescription(), it won't exist in the HTML. We must wait a bit of time before running it again. If there was something like DocumentApp.flush() (similar to how the Spreadsheet App has the same function), it might resolve this issue and we wouldn't need to crash.
throw "Image was missing an alt description. Run again."
}
var html = getGoogleDocumentAsHTML();
var regex = new RegExp('<img alt="' + altDescription + '" src="([^"]+)"');
var matches = regex.exec(html);
if (matches) {
return matches[1];
} else {
return null;
}
}
function getGoogleDocumentAsHTML() {
var id = DocumentApp.getActiveDocument().getId() ;
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
return html;
}
There is obviously room for improvement with the script (e.g. not making it crash), but this was good enough for my use-case.

Google geocoding returns zero results, Unity3D

I am trying to connect to google maps api and get lant/long of place, but no matter what I'm trying to get, I receive ZERO_RESULTS every time. For example if I type
http://maps.googleapis.com/maps/api/geocode/json?address=Moscow+Tverskaya+18 into browser, it gives me correct result, but if I'm trying to send the exact same string via WWW class from unity I get zero results.
IEnumerator GetGoogleCoords() {
var url = "http://maps.googleapis.com/maps/api/geocode/json?";
var qs = "";
// qs += "address=" + savedAddress;
qs += "address=Moscow +Tverskaya+18";
var req = new WWW(url + "?" + qs);
Debug.Log(url + qs);
yield return req;
Debug.Log(req.text);
}
I tried every request and in every order
You have an extra "?" in your url as #Engerlost said.
This post is about how to prevent doing similar mistakes again.
Best programming practice would be to build the full url not in WWW constructor but in a separate line.
var url = "http://maps.googleapis.com/maps/api/geocode/json?";
var qs = "address=Moscow +Tverskaya+18";
var fullUrl = url + "?" + qs
var request = new WWW(fullUrl);
That is, one line should contain only one job. Which makes it much easier to manage the code. In your case, it gets much easier to debug and see there is an error building the full url. Now you are able to easily add a Debug.Log if you suspicious about final url which goes into WWW as parameter.
Debug.Log("Request url: " + fullUrl);
And you would easily see the resulting url contains two "?" characters.