1. Brett Weaver
  2. PowerBuilder
  3. Thursday, 19 December 2024 06:04 PM UTC

Hi There

Apologies in advance, this is probably something obvious as I am not used to calling REST API's. I have written code based on the examples given in application techniques. The situation is that the code works sometimes but not others.

Here is a log of attempts:

ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
File Bugfile.PDF created with size of 14987833
ProcessedBugfile.PDF Length 66 {"data":[],"errors":["No Session exists for Access Token. (401)"]}
File Bugfile.PDF created with size of 14987833

So 2 in 12 times the code  below worked fine.

If anyone would like to test it themselves I can send the clientid and client secret separately. 

Maybe I have something misspelt or missed somehow.. But sometimes it works!

The URL works fine in Postman every time. I have tried to copy all the settings from Postman but...

I would really appreciate some assistance here as I have been looking at this for days.

 

 

 

 

OAuthClient loac_Client
TokenRequest ltr_Request
TokenResponse ltr_Response
HttpClient lhc_Client
String ls_TokenType,ls_accesstoken2
String ls_Body, ls_type, ls_description, ls_uri, ls_state, ls_Url
Long ll_return,ll_count


Long ll_FileNum, ll_rtn, ll_loop, ll_len
Dec{0} ldc_Count, ldc_Length
Blob lb_temp
String ls_response, ls_Length

 

loac_Client = Create OAuthClient
lhc_Client = Create HttpClient
//Step 1: Get the RESTful server access token.

ltr_Request.tokenlocation = "https://training.simpli.org.nz/api/oauth/v1/oauth2-token"
ltr_Request.Method = "POST"
ltr_Request.secureprotocol = 0
ltr_Request.clientid = "xxxxxxxxxxxxxxxxxxxx"
ltr_Request.clientsecret = "xxxxxxxxxxxxxx"
ltr_Request.UserName = "username"
ltr_Request.Password = "password123"
ltr_Request.scope = "testcode"
ltr_Request.granttype = "client_credentials"
ltr_request.setheader("content-type", "application/json; charset=utf-8")
//ltr_request.setheader("Transfer-Encoding", "chunked")
ltr_request.setheader("Connection", "keep-alive")
ltr_request.setheader("Strict-Transport-Security","max-age=31536000")
ltr_request.setheader("Content-Security-Policy","upgrade-insecure-requests;")
ltr_request.setheader("Pragma","no-cache")
ltr_Request.setheader("X-Content-Type-Options","nosniff")
ltr_request.setheader("Cache-Control","no-store, no-cache, must-revalidate")
ltr_request.setheader("Set-Cookie","app_session=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/")

ll_Return = loac_Client.AccessToken( ltr_Request, ltr_Response )
If ll_Return = 1 and ltr_Response.GetStatusCode () = 200 Then
ls_AccessToken2 = ltr_Response.GetAccessToken()
ls_TokenType = ltr_Response.GetTokenType( )

 

lhc_Client = Create HttpClient


ls_url = "https://training.simpli.org.nz/api/go/1.0/submission_file/submission_doc_guid-f8e75d7a-e725-7974-e576-adddd019bd57"
lhc_Client.ClearRequestHeaders()
lhc_Client.SetRequestHeader( "Authorization", ls_TokenType + " " + ls_AccessToken2)
lhc_Client.SetRequestHeader("Accept-Encoding", "gzip, deflate, br")
lhc_Client.SetRequestHeader("Connection", "keep-alive")
lhc_Client.SetRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate")
lhc_Client.SetRequestHeader("Strict-Transport-Security","max-age=31536000")
lhc_Client.SetRequestHeader("Vary","Authorization")
lhc_Client.SetRequestHeader("Content-Security-Policy","upgrade-insecure-requests;")
lhc_Client.SetRequestHeader("Content-Transfer-Encoding","binary")

// Not to read data automatically after sending request (default is true)
lhc_Client.autoreaddata = false

ll_rtn = lhc_Client.sendrequest( "GET", ls_url )
//Receive 16KB data every time
ll_loop = 1024 * 16
string ls_filename
ls_filename = 'Bugfile.PDF'
//Write data to the file, because the blob variable is not suitable for large data
ll_FileNum = FileOpen(ls_filename, StreamMode!, Write!, LockWrite!, Replace!)
string ls_lastwritten
Do While ( ll_rtn = 1 )
lb_temp = Blob ( "" )
ll_rtn = lhc_Client.ReadData( lb_temp, ll_loop)
if ll_rtn = 0 then exit
if ll_rtn = -1 then exit

FileWrite(ll_FileNum, lb_temp)
ls_lastwritten = string(lb_temp,EncodingUTF8!)
yield()
Loop


FileClose(ll_FileNum)
if filelength(ls_filename) < 2000 then
MLE_1.text += '~r~nProcessed'+ls_filename+' Length '+string(filelength(ls_filename))+' '+ls_lastwritten

else
mle_1.text += '~r~nFile '+ls_filename+' created with size of '+string(filelength(ls_filename))
end if
If IsValid ( lhc_Client ) Then Destroy ( lhc_Client )
else
string ls_bodyresp
ltr_response.getbody(ls_bodyresp)
mle_1.text = 'Return: '+string(ll_return)+ ' Status Code: '+string( ltr_Response.GetStatusCode () )+ls_bodyresp
end if

 


Responses (1)
  1. Likes
  2. Latest
  3. Oldest
Loading...

Find Questions by Tag

.EXE .NET 6.0 .NET Assembly .NET Core 3.1 .NET Core Framework .NET DataStore .NET Std Framework 32-bit 64-bit ADO.NET AEM AI Algorithm Amazon AWS Android Apache API APK App Store App Store (Apple) Appeon Workspace Appeon Xcelerator Plug-in Architecture Array ASE Asynchronous Methods Authentication AutoBuild AutoCompiler Automated Testing Automation AutoScript Azure Barcode Base64 Batch BigData BLOB Branch & Merge Browser Bug Build Button C# C# Class Importer C# Editor C# Model generator Calendar Camera Certificate Chrome Citrix Class Client Client/Server Cloud Cluster Collection COM Command Line Compiler Compression Computed Field Configuration Controls Cookies Cordova Crash Cross-Platform Crosstab CSharpAssembly CSharpObject CSS CSV Cursor Data Database Database Driver Database Painter Database Profile Database Provider DataObject DataSource DataStore DataStore (C#) DataStore (PS) DataType DataWindow DATE DATETIME DB2 Debug Debugger Debugging Deployment Design DLL DO-WHILE Dockable Docker Documentation DOUBLE Download DragDrop Edge Edit Style Editor Elevate Conference Email Embedded SQL Emulator Encoding Encryption Enhancement Request Entity Entity Framework ERP Error Event Event Handler Event Handling Excel Exception Export Expression External Functions F# Field File File Access Filter Firefox Firewall Font FOR-NEXT Foreground Format Function Garbage Collection GeoLocation Git Graph HANA Hash Header HTML/5 HTTP/S HTTPClient Icon IDE Identity IIS IMAPI Import InfoMaker Inheritance Installation Integer IntelliSense Interface Internet Internet Explorer iOS IPA iPad iPhone IWA J# Java JavaScript JBoss JDBC JOIN JSON JSONGenerator JSONParser Kestrel Label Lambda Large File LDAP Library License LINQ Linux OS Load Balancing Localization Localized PBVM Log In Log Out Logging LONG LONGLONG macOS MAPI Maps MDI Memory Memory Leak Menu Merge MessageBox Messagging Method Migration MIME TYPE Mobile Model ModelStore ModelStore (C#) MSOLEDBSQL Multi Threading MVC MySQL n-Tier Namespace NativePDF NVO OAuth ODATA ODBC Office Offline OLE OLEDB Online Open Source OpenAPI OpenSSL Oracle OrcaScript Other Outlook Output Package Parameter Patch PayPal PB Classic PB Native PB.NET PBC PBD PBDOM PBG PBJVM PBL PBNI PBORCA PBVM PBX PDF Performance Permission PFC Picture Pipeline Play Store (Google) Plugin Popup Port POST PostgreSQL PowerBuilder PowerBuilder (Appeon) PowerBuilder (SAP) PowerBuilder Compiler PowerBuilder Runtime PowerClient PowerScript (PS) PowerScript IDE PowerScript Migrator PowerServer PowerServer Mobile PowerServer Toolkit PowerServer Web PowerServerLabel Print Properties Proxy Publish PULL PUSH Query Regression Release Renew Resize Response REST Retrieve RibbonBar RibbonBar Builder Rich Text Roadmap RPC Runtime Packager SaaS Scaffolding Script SDI SDK Security Server Service Session Single Sign-on Size SMTP SMTPClient SnapDevelop SOAP Sort Source Code Speech Recognition SQL SQL Anywhere SQL Server SqlBuilder SqlExecutor SQLite SqlModelMapper Storage Stored Procedure Subscription SVN Swagger Syntax TabbedBar TabbedView Tablet TabPage Target TE Control Testing Text TFS Theme TIME Timer TLS/SSL Tomcat TortoiseGit TortoiseSVN Transaction Transparency Trial Trigger TRY-CATCH TX Control Type UI ULONG UltraLite Uninstall Unit Test Unit Testing UNIX OS Update Upgrade Upload URL User Center User Object UWP Validation VARCHAR Variable Versioning Visual Studio Visual Studio Code VM Voice Warning WCF Web API Web Extensions Web Service WebBrowser WebForms WebLogic WebSphere WildFly WinAPI Window Windows OS WinForms Wizard Workgroup Workspace WPF XCODE XHTML XML Zoom

Helpful?

If a reply or comment is helpful for you, please don’t hesitate to click the Helpful button. This action is further confirmation of their invaluable contribution to the Appeon Community.