Page 1 of 1

send request to get API Token

Posted: Thu Sep 12, 2019 12:32 pm
by MTswitch
Hi,
i want to send post to request to Api to catch a Token
this is my script and i dont know why i received invalid request from the Api. i guss i wrote something wrong in authoriziation but i am not sure

Code: Select all

	
	var myPostData = {};

	// Add Values
	myPostData['key1'] = "value1";
	myPostData['key2'] = "value2";

	var myJSON = JSON.stringify(myPostData);
	job.log(-1, myJSON );
	
	var theHTTP = new HTTP();  
	theHTTP.url = 'ApiEndPoint';
	theHTTP.authScheme = HTTP.BasicAuth;
	theHTTP.user = "username";
	theHTTP.password  = "password";
	theHTTP.authorization = "authorization string";

	theHTTP.addHeader( "Content-Type", "application/x-www-form-urlencoded" );
	var postBody = new ByteArray( myJSON , "UTF-8" );
	theHTTP.setPostData( postBody,"application/x-www-form-urlencoded" );
	theHTTP.post();
	
	
	while( !theHTTP.waitForFinished( 3 ) )
	{
		job.log( 1, "Refresh token in progress" );
	}

	var theServerResponse = theHTTP.getServerResponse().toString();
	job.log(-1, "Server response: " + theHTTP.getServerResponse().toString("UTF-8"));

Thanks for your comments

Re: send request to get API Token

Posted: Mon Sep 16, 2019 9:05 am
by freddyp
There are many things that could be wrong: is the endpoint correct, do not you have to add the authorization string to a special header, does not the content-type have to be application/json, ...? Without the documentation of the API it is impossible to help.

Re: send request to get API Token

Posted: Mon Sep 16, 2019 11:09 am
by MTswitch
freddyp wrote: Mon Sep 16, 2019 9:05 am There are many things that could be wrong: is the endpoint correct, do not you have to add the authorization string to a special header, does not the content-type have to be application/json, ...? Without the documentation of the API it is impossible to help.
Hi
The endpoint is correct i checked it. I checked that with postman and it works.
in postman in Authorization tab, Type is Basic and username password and there are two keys and values in Body Tab
i want to write this structure in switch

Re: send request to get API Token

Posted: Thu Sep 19, 2019 10:17 am
by MTswitch
i solved the problem and i explain what did i do.
first of all when u use basic authentication method, u dont need to write theHTTP.authorization just put username in theHTTP.user and password in theHTTP.password and theHTTP.authScheme is HTTP.BasicAuth in this form username and password are encoded in Base64.

But if u have username and password in Base64 write

Code: Select all

 theHTTP.authScheme = HTTP.OauthAuth ;
 theHTTP.authorization = "Authoriziation type (Bearer) " + username and password in Base64;
and if u want send body to endpoint use this code:

Code: Select all

var Body = "***";
var postBody = new ByteArray(Body);
theHTTP.setPostData( postBody,"application/x-www-form-urlencoded" );