HTMLDialog - make a get request with Authentication header

Here is an untested example …

ADD: The example(s) below have been simplified per …

  • You could probably drop the dialog argument and just use self within the methods (which refers to the instance itself within instance methods. (The example was adapted from some other old code examples.)

… and are available here:


Older complex example (...click to expand...)
module SomeAuthor::SomePlugin

  AuthDialog = Class.new( defined?(UI::HtmlDialog) ? UI::HtmlDialog : UI::WebDialog )
  class AuthDialog

    # (IETF) RFC7617 : The ‘Basic’ HTTP Authentication Scheme
    # https://tools.ietf.org/html/rfc7617

    if self < UI::WebDialog
    
      # using the Standard Ruby Library Net::HTTP classes ...
      require 'net/http' # loads 'uri'

      def get_page(dialog, url, username, password, **form)

        fail(ArgumentError, "username cannot contain a colon!",caller) if username.include?(':')

        uri = URI(url)
        req = Net::HTTP::Get.new(uri)
        req.basic_auth(username, password)
        req.set_form_data(form)

        UI.start_timer(0,false) do
          @res = Net::HTTP.start(uri.hostname, uri.port) {|http|
            http.request(req) do |response|
              dialog.set_html(response.body)
              dialog.show if !dialog.visible?
            end
          }
        end

      end
  
    else

      # using the SketchUp Ruby API HTTP classes v2017+ ...
      require 'uri'
      require 'base64'

      def get_page(dialog, url, username, password, **form)

        fail(ArgumentError, "username cannot contain a colon!",caller) if username.include?(':')

        uri = URI(url)
        creds = "#{username}:#{password}"

        @req = Sketchup::Http::Request.new(uri.to_s, Sketchup::Http::GET)
        @req.headers= { 'Authorization' => 'Basic '<< Base64.encode64(creds) }
        @req.body= URI.encode_www_form(form)

        @req.start do |request, response|
          dialog.set_html(response.body)
          dialog.show if !dialog.visible?
        end

      end

    end

  end # class AuthDialog
end # module namespaces

… and a call to the method would be like …

get_page( 
  dlg, "http://www.mywebsite.com",
  'somebody', 'suchandsuch',
  'search' => 'some_query', 'lang' => Sketchup.get_locale
)

* … of course the form data fields can be whatever they need to be for the target webpage.