Closer to Code

Tag: https (page 2 of 3)

Using Savon Rb to communicate with SOAP client (http basic authentication and no WSDL file)

Most of the time, when we connect to webservices via SOAP (via SOAP! via SOAP! ;)), we have a WSDL file either local or downloaded from a server. But sometimes we need to connect to SOAP server which does not have this file and it is secured with http basic authentication.

To communicate with SOAP I use Savon Rb. It is easy and relatively fast. However in documentation there is nothing about communication with http basic authentication protected resources.

Although setting things up is really easy. First authentication:

@soap_client = Savon::Client.new do
  # Set basic authorization
  http.auth.basic "user_name", "password"
end

and non-wsdl connection:

@soap_client = Savon::Client.new do
  wsdl.endpoint = "http://service.example.com"
  wsdl.namespace = "http://v1.example.com"
end

and that’s all. Now we can execute remote method like this:

@soap_client.request :get_items

or with params:

@last_response = @soap_client.request :get_items do
  soap.body = {
    :param_1 => "value_1",
    :param_2 => "value_2",
  }
end

Ruby – Sprawdzanie dostępności linku ze znakami z UTF-8

Przed kilkoma dniami natrafiłem na pewien problem. Mianowicie open-uri i metoda open nie działają dla znaków z utf-8 (czyli między innymi dla stron gdzie fragment URLa ma “ogonki”). W związku z czym, taki fragment kodu będzie zawsze zwracał fałsz, mimo tego, że pod adresem istnieje strona:

# coding: utf-8
# Wesja rzecz jasna uproszczona - bez obsługi timeoutów itd
url = 'http://www.nina.gov.pl/nina/czołówka'
io_thing = open(url)
correct = io_thing.status[0] == '200'

Zasadniczo bez obsługi błędów będziemy dostawać taki oto wyjątek:

 bad URI(is not URI?): www.nina.gov.pl/nina/czołówka (URI::InvalidURIError)

Rozwiązanie tego problemu może nie jest zbyt eleganckie ale działa:

# coding: utf-8
require 'open-uri'
require 'net/http'

url = 'http://www.nina.gov.pl/nina/czołówka'
url = URI.parse(URI.encode(url))

correct = false
level = 0
while(!correct && level < 10) do
  requst = Net::HTTP.new(url.host, url.port)
  if url.to_s.include?('https')
    requst.use_ssl = true
    requst.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  
  requst.start do |http|
    http = http.head(url.request_uri)
    if http.code == "200"
      correct = true
    else
      url = URI.parse(URI.encode(http.header['location'] ))
    end
    level += 1
  end
end

http.head nie podąża za przekierowaniami więc musimy robić to sami.

Olderposts Newerposts

Copyright © 2021 Closer to Code

Theme by Anders NorenUp ↑