Page 1 of 1

HTTPHeaders() Procedure

Posted: Mon Sep 04, 2023 4:55 pm
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.

Re: HTTPHeaders() Procedure

Posted: Mon Sep 04, 2023 5:34 pm
by nsstudios
+1
A "byref" map param like ExtractRegularExpression does for arrays would be really nice.

Re: HTTPHeaders() Procedure

Posted: Mon Sep 04, 2023 11:15 pm
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
.

Re: HTTPHeaders() Procedure

Posted: Mon Sep 04, 2023 11:32 pm
by nsstudios
That's very simple indeed!
It will make it easy to add it to the language. :)