How to get the location header in Google Apps Script - redirect

I was experimenting with building a Google Spreadsheet where:
Column A is a list of URLs that should be 301 redirected
Column B was our intended URL to be redirect to
Column C is the server response code when hitting Column A
Column D is the URL that was ultimately served up when hitting Column A
Column E is a Boolean for B and D matching
I'm having problems with populating column D. Here is what I tried:
function getHeaders(tURL) {
var response = UrlFetchApp.fetch(tURL);
var tHeaders = response.getAllHeaders();
}
I was expecting that "location" would be in the response header. But it seems this method only returns a handful of server response headers. I get: X-Frame-Options, Date, P3P, Content-Length, Expires, X-XSS-Protection, Content-Encoding, Alternate-Protocol, Set-Cookie (array), Content-Type, Server, Cache-Control.
Question
Any suggestions on another way to get to location? Or an alternate idea on how to determine where the url was redirected to?

You need to use fetch(url, params) method of UrlFetchApp class and supply followRedirects parameter set to false:
var response = UrlFetchApp.fetch(tURL, {'followRedirects':false});
followRedirects defaults to true, and thus your request returns the headers and content of the page it was redirected to, not the requested page. That is why you do not see the Location header there.

Related

How to get token value of string type from rest response

Delphi 10.4.2
REST server generates new tokens every 2-3 hours and client must login in order to get new token. In Swagger and Postman server returns HTTP 200:
Response of server is uuid string like "d14e02b7-ae5e-11ed-8105-005056b4f1d1"
I create new query parameters on page "Parameters" of Rest Debugger. Server returns HTTP 200 but in the tab "Tabular data" if I click on the value caption to select root element and then press "Apply" button get error:
Response RootElement, "value", is not a valid path for the response JSON.
If I place rest components(RecsClient, RestRequest, RestResponse, RestAdapter) on the form and RootElement property of RestResponse is set to 'value' or 'resultData' I get the same error.
But if I empty RootElement property of RestResponse component and execute RestRequest component I get HTTP 200 and token value appears in FDMem component but how then from RestResponse extract uuid single string value?
SOLUTION:
this code works:
var token:String;
token:=RestResponse1.JSONValue.Value;
or this:
var
JV: TJSONValue;
str1,str2: string;
begin
str1:= fRefGoods.rrespLogin.Content;
JV:=TJSONObject.ParseJSONValue(str1);
str2:=JV.Value;
the confusion was caused by not knowing that "d14e02b7-ae5e-11ed-8105-005056b4f1d1" is a valid JSON-string. I thought it was necessary JSON-string be enclosed in {} curly brackets and data presented as JSON-Pairs separated by commas. As it turned out I was wrong.
JSONLint also identifies it as valid JSON-string.

how to put param(body) in restangular?

I have api that required parameter in body, so I need to put that values in restangular, I have tried this
function deleteAccount(){
$log.log(accountIdDelete);
Restangular.one(apiDeleteAccount).customDELETE(
undefined,
[
{id : accountIdDelete},
{ContentType:'application/x-www-form-urlencoded'}
]).then(function(response){
$log.log(response);
var index = vm.account.indexOf(accountIdDelete);
if (index > -1) vm.account.splice(index, 1);
$('#deleteAccount').modal('hide');
});
}
What I'm trying is basicly tried to delete the data using id, I need that data Id put it in body request so that the api can detect select the data and delete it. but the code above that doesn't pass the value to the server? is there any way to put request body in restangular?
Based on my knowledge and searching on the internet, NgResource and restangular doesnt' support to set body into delete request, the only support for POST request to put data into the body, Correct me if I'm wrong but this is based on this answer :
https://stackoverflow.com/a/16203738/2652524

How do I add a field for a header for an authentication token for Swagger UI?

My team has just started creating RESTful services for data that has previously been handled by a large monolithic legacy application. We want to document the api with Swagger UI and I have set up with one problem.
I need to pass a SAML token as a header parameter, otherwise when we try to click on the "Try it out!" button I get a 401 Authentication error. How do I add a field to the Swagger UI so that someone can put a String for a SAML token to be sent in the request?
This is actually really easy. I saw references to the answer in the documentation but I didn't really understand what it was saying. There is a field at the top next to where your service URL goes and you can use that field to input a string to pass as a header value. That input field has an id of #input_apiKey.
Then in the index.html file you just add a line to the addApiKeyAuthorization() javascript function telling it to take the value of that field and pass it as whatever value you need.
Example:
function addApiKeyAuthorization(){
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
swaggerUi.api.clientAuthorizations.add("samlToken", new SwaggerClient.ApiKeyAuthorization("samlToken", key, "header"));
swaggerUi.api.clientAuthorizations.add("Content-Type", new SwaggerClient.ApiKeyAuthorization("Content-Type", "application/json", "header"));
swaggerUi.api.clientAuthorizations.add("Accept", new SwaggerClient.ApiKeyAuthorization("Accept", "application/json", "header"));
}
}
$('#input_apiKey').change(addApiKeyAuthorization);
This sets the Content-Type and Accept headers to the same values for every request, and takes the value in that input field at the top of the page in the green header and sets it as my SAML token. So now if I paste in a valid SAML string my request works and I get data back!

POST to ASP.NET WebAPI using Fiddler2

I have a class that models exactly the entity I have in the database. I have a stored procedure that takes in parameters for a new row and returns all the settings in the table which in turn populates my repository. I am able to see the results of GET, PUT and DELETE in the List of type Setting that is in memory. I am noticing first that even when I close Visual Studio and reopen and run the project, sometimes, the List is still in the state it was before. It is not repopulating from the database so I'm not sure why that is first of all... Secondly, I can't seem to get POST to work from Fiddler unlike the other HTTP verbs. I DO see the values from Fiddler show up in the code below but I get the error: Invalid URI: The format of the URI could not be determined. I get the same error if I pass an ID or not.
Here is what I put into Fiddler:
POST localhost:54852/api/settings
Request Headers
User-Agent: Fiddler
Content-type: application/x-www-form-urlencoded
Host: localhost:54852
Content-Length: 149
Request Body
ID=0&Category=Dried%20Goods&Sub_Category=Other&UnitSize=99&UnitOfMeasureID=999&Facings=true&Quantity=true&EverydayPrice=999.99&PromotionPrice=111.11
PostSetting function within my SettingsController
public HttpResponseMessage PostSetting(Setting item)
{
item = repository.Add(item);
var response = new HttpResponseMessage<Setting>(item) { StatusCode = HttpStatusCode.Created };
string uri = Url.Route("DefaultApi", new { id = item.ID });
response.Headers.Location = new Uri(uri);
return response;
}
Should I create a new procedure that gets the MAXID from the database and use that as the NEW ID in the line above where a new ID is created?
You need to create a JSON representation of the Setting class or item that you are wanting to test with use Fiddler (now a Telerik product) and use the Composer tab.
Next you will want to perform a POST to the following URL:
http://[your base url]/api/settings
and pass the JSON formatted setting class.
You can see an example of this here: ASP.NET Web API - Scott Hanselman
Here is a short video showing how to achieve it easily
get and post to webapi from fiddler

Sinatra not passing header with redirect

I have a simple Sinatra proxy, which when an endpoint is called, will redirect to another endpoint on the same Sinatra proxy.
When I make a request with a header, the proxy doesn't seem to pass this header through to the second endpoint when the request redirects in the first. This is my code:
get '/first' do
# get the header from the request
username = env['HTTP_USERNAME']
# set the header for the response
response['username'] = username
redirect '/second'
end
get '/second' do
# This doesn't exist when redirected from /first
puts env['HTTP_USERNAME']
# Here is a list of all headers
env.each_key do |key|
puts "KEY: #{key} VALUE: #{env[key]}" unless key.nil?
end
"DONE"
end
Any tips would be greatly appreciated.
Thanks
That is intentionally. redirect triggers an HTTP redirect, a new request will be fired. Also, passing on env values is done via modifying env, not response.
The main question is, what do you mean by header? Request header or response header? From your example I figure you mean request header, therefore response['username'] = username should be request.env['username'] = username. You could then replace redirect '/second' with request.path_info = '/second'; pass to do some sort of internal redirect. If you don't pass the value on to another Rack middleware/endpoint, you could also store the user name in an instance variable.
get '/first' do
request.path_info = '/second'
pass
end
get '/second' do
puts request.env['HTTP_USERNAME']
"DONE"
end