
ogit2
Novice
Aug 15, 2017, 7:24 AM
Post #6 of 8
(3508 views)
|
Re: [jxm28] How to access an API with Perl?
[In reply to]
|
Can't Post
|
|
Hi Another way is below. This is where I too need help as we need to use restful web services with bearer token. The first set of code is my attempt to replicate c# code (which works) using perl. What am I doing incorrectly? I have not copied the entire c# program but just the key part I am trying to replicate. The perl program is not sending the data correctly so the response I get back is 'error' => 'unsupported_grant_type. I am guessing I have not put the text 'application/x-www-form-urlencoded' or '/token' in the right places in my attempts. non-coder so limited understanding of c# or perl. Perl Code Attempt 1 -----------
use JSON; use MIME::Base64; use REST::Client; use Data::Dumper; my $username = 'someusername'; my $password = 'somepassword'; my $headers = {Accept => 'application/x-www-form-urlencoded', grant_type => "password", username => $username, password => $password}; my $client = REST::Client->new(); $client->setHost('https://api.service.com'); $client->GET( '/token', $headers ); my $response = from_json($client->responseContent()); print Dumper($response); Perl Code Attempt 2
use JSON; use MIME::Base64; use REST::Client; use Data::Dumper; my $username = 'someusername'; my $password = 'somepassword'; my $headers = {grant_type => 'password', username => $username, password => $password}; my $client = REST::Client->new(); $client->setHost('https://api.service.com'); $client->addHeader('Content-Type', 'application/x-www-form-urlencoded' ); $client->POST ('/token','',$headers); my $response = from_json($client->responseContent()); print Dumper($response); c# Equivalent Code - This Works --------------------------------------
public async Task<TokenResponse> Login() { using (var client = new HttpClient()) { client.BaseAddress = this.baseUri; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var content = new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", this.username), new KeyValuePair<string, string>("password", this.password) }); var response = await client.PostAsync("/token", content); if (response.StatusCode != HttpStatusCode.OK) { return this.userObject; } var responseContent = await response.Content.ReadAsStringAsync(); this.userObject = new JavaScriptSerializer().Deserialize<TokenResponse>(responseContent); return this.userObject; } }
(This post was edited by ogit2 on Aug 15, 2017, 7:55 AM)
|