DDD
DDD

Reputation: 1462

Supply key-value pairs to http get request

I'm sure there's an easy answer to this but the Google Script docs are a little lacking at the moment. Anyway, here's a question. I have a simple key-value map:

var params = {var1: "value1", var2:"value2"};

Now I want to send that data via a http request. If I use a POST then it's all easy, I can supply the payload as an option and it gets nicely encoded for me:

UrlFetchApp.fetch(url, {method: "post", payload: params});

But how can I do the equivalent with a GET request?

In jQuery I'd use jQuery.param and concatenate it onto the url. Is there a helper method in Google Script?

Upvotes: 0

Views: 1234

Answers (1)

Joscha
Joscha

Reputation: 4693

How about:

var params = {'a':1, 'speciöl':'%'};
var query = [];
for(var key in params) {
  if(Object.prototype.hasOwnProperty.call(params,key)) {
    query.push(encodeURIComponent(key)+"="+encodeURIComponent(params[key].toString()));
  }
}
var url = "http://bla" + "?" + query.join("&");

Empty values are not filtered and the serilaization is shallow.

Upvotes: 1

Related Questions