HTTPHeaders() Procedure

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Quin
Addict
Addict
Posts: 1131
Joined: Thu Mar 31, 2022 7:03 pm
Location: Colorado, United States
Contact:

HTTPHeaders() Procedure

Post by Quin »

Hi,
Currently, if I want to parse HTTP headers from a request, I need to do a ton of (really ugly) string parsing. Like, to get Content-Disposition, I'd have to call HTTPInfo, then do a FindString for "Content-Disposition:", then extract the header value using Mid or StringField or some such method. It would be a lot easier if we had a function, something like hTTPHeaders, that returns us a map of header names and their values, basically in the same format that you can supply headers to HTTPRequest in.
nsstudios
Enthusiast
Enthusiast
Posts: 309
Joined: Wed Aug 28, 2019 1:01 pm
Location: Serbia
Contact:

Re: HTTPHeaders() Procedure

Post by nsstudios »

+1
A "byref" map param like ExtractRegularExpression does for arrays would be really nice.
infratec
Always Here
Always Here
Posts: 7588
Joined: Sun Sep 07, 2008 12:45 pm
Location: Germany

Re: HTTPHeaders() Procedure

Post by infratec »

Use this if you really need it:

Code: Select all

CompilerIf #PB_Compiler_IsMainFile
  EnableExplicit
CompilerEndIf

Procedure.i HTTPHeaders(Request.i, Map Headers$())
  
  Protected.i l
  Protected Header$, Line$
  
  
  Header$ = HTTPInfo(Request, #PB_HTTP_Headers)
  
  l = 1
  Repeat
    Line$ = StringField(Header$, l, #CRLF$)
    l + 1
    If FindString(Line$, ":")
      AddMapElement(Headers$(), StringField(Line$, 1, ":"))
      Headers$() = LTrim(StringField(Line$, 2, ":"))
    EndIf
  Until Line$ = ""
  
  ProcedureReturn MapSize(Headers$())
  
EndProcedure


CompilerIf #PB_Compiler_IsMainFile
  
Define HTTPRequest.i
NewMap Headers$()

HttpRequest = HTTPRequest(#PB_HTTP_Get, "https://www.purebasic.com")
If HttpRequest
  
  Debug HTTPHeaders(HTTPRequest, Headers$())
  ForEach Headers$()
    Debug MapKey(Headers$()) + "->" + Headers$()
  Next
  
  FinishHTTP(HTTPRequest)
EndIf
CompilerEndIf
.
nsstudios
Enthusiast
Enthusiast
Posts: 309
Joined: Wed Aug 28, 2019 1:01 pm
Location: Serbia
Contact:

Re: HTTPHeaders() Procedure

Post by nsstudios »

That's very simple indeed!
It will make it easy to add it to the language. :)
Post Reply