문제

제 고객이 제3자 API를 Rails 앱에 통합해 달라고 요청했습니다.유일한 문제는 API가 SOAP를 사용한다는 것입니다.Ruby는 기본적으로 REST를 선호하여 SOAP를 삭제했습니다.그들은 Java-Ruby 브리지와 함께 작동하는 것으로 보이는 Java 어댑터를 제공하지만 가능하다면 모든 것을 Ruby로 유지하고 싶습니다.Soap4r을 찾아봤는데 평판이 조금 안 좋은 것 같습니다.

그렇다면 SOAP 호출을 Rails 앱에 통합하는 가장 좋은 방법은 무엇일까요?

도움이 되었습니까?

해결책

우리는 내장된 것을 사용했습니다. soap/wsdlDriver 클래스는 실제로 SOAP4R입니다.개 느리지만 정말 간단합니다.gems/etc에서 얻는 SOAP4R은 동일한 것의 업데이트된 버전일 뿐입니다.

예제 코드:

require 'soap/wsdlDriver'

client = SOAP::WSDLDriverFactory.new( 'http://example.com/service.wsdl' ).create_rpc_driver
result = client.doStuff();

그게 다야

다른 팁

내가 지 었지 사본 Ruby를 통해 SOAP 웹 서비스와 상호 작용하는 것을 최대한 쉽게 만듭니다.
꼭 확인해 보시길 권합니다.

Handsoap에서 Savon으로 전환했습니다.

여기에는 일련의 블로그 게시물 두 클라이언트 라이브러리를 비교합니다.

나는 또한 추천한다 사본.결과 없이 Soap4R을 처리하려고 너무 많은 시간을 보냈습니다.기능이 크게 부족하고 문서도 없습니다.

Savon이 저에게 답입니다.

노력하다 SOAP4R

방금 Rails Envy Podcast(ep 31)에서 이에 대해 들었습니다.

Savon을 사용하여 3시간 이내에 작업을 완료했습니다.

Savon 홈페이지의 시작하기 문서는 정말 따라하기 쉬웠고 실제로 제가 본 것과 일치했습니다(항상 그런 것은 아님).

켄트 시빌레프 데이터노이즈 또한 Rails ActionWebService 라이브러리를 Rails 2.1(및 그 이상)로 포팅했습니다.이를 통해 자신만의 Ruby 기반 SOAP 서비스를 노출할 수 있습니다.그는 브라우저를 사용하여 서비스를 테스트할 수 있는 스캐폴드/테스트 모드도 가지고 있습니다.

나는 같은 문제를 겪고 있었고 Savon으로 전환한 다음 공개 WSDL에서 테스트했습니다(저는 http://www.webservicex.net/geoipservice.asmx?WSDL) 그리고 지금까지는 정말 좋았습니다!

https://github.com/savonrb/savon

저는 승인 테스트를 위해 가짜 SOAP 서버를 만들어야 했을 때 Ruby에서 SOAP를 사용했습니다.이것이 문제에 접근하는 가장 좋은 방법인지는 모르겠지만 제게는 효과가 있었습니다.

저는 Sinatra gem을 사용했습니다(Sinatra를 사용하여 모의 엔드포인트를 만드는 방법에 대해 썼습니다). 여기) 서버용 및 노코기리 XML 관련(SOAP는 XML과 함께 작동함)

그래서 처음에는 두 개의 파일을 만들었습니다(예:config.rb 및 response.rb) 여기에 SOAP 서버가 반환할 미리 정의된 답변을 넣었습니다.~ 안에 구성.rb WSDL 파일을 문자열로 넣었습니다.

@@wsdl = '<wsdl:definitions name="StockQuote"
         targetNamespace="http://example.com/stockquote.wsdl"
         xmlns:tns="http://example.com/stockquote.wsdl"
         xmlns:xsd1="http://example.com/stockquote.xsd"
         xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
         xmlns="http://schemas.xmlsoap.org/wsdl/">
         .......
      </wsdl:definitions>'

~ 안에 응답 .rb SOAP 서버가 다양한 시나리오에 대해 반환할 응답에 대한 샘플을 넣었습니다.

@@login_failure = "<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <LoginResponse xmlns="http://tempuri.org/">
            <LoginResult xmlns:a="http://schemas.datacontract.org/2004/07/WEBMethodsObjects" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <a:Error>Invalid username and password</a:Error>
                <a:ObjectInformation i:nil="true"/>
                <a:Response>false</a:Response>
            </LoginResult>
        </LoginResponse>
    </s:Body>
</s:Envelope>"

이제 실제로 서버를 어떻게 생성했는지 보여드리겠습니다.

require 'sinatra'
require 'json'
require 'nokogiri'
require_relative 'config/config.rb'
require_relative 'config/responses.rb'

after do
# cors
headers({
    "Access-Control-Allow-Origin" => "*",
    "Access-Control-Allow-Methods" => "POST",
    "Access-Control-Allow-Headers" => "content-type",
})

# json
content_type :json
end

#when accessing the /HaWebMethods route the server will return either the WSDL file, either and XSD (I don't know exactly how to explain this but it is a WSDL dependency)
get "/HAWebMethods/" do
  case request.query_string
    when 'xsd=xsd0'
        status 200
        body = @@xsd0
    when 'wsdl'
        status 200
        body = @@wsdl
  end
end

post '/HAWebMethods/soap' do
request_payload = request.body.read
request_payload = Nokogiri::XML request_payload
request_payload.remove_namespaces!

if request_payload.css('Body').text != ''
    if request_payload.css('Login').text != ''
        if request_payload.css('email').text == some username && request_payload.css('password').text == some password
            status 200
            body = @@login_success
        else
            status 200
            body = @@login_failure
        end
    end
end
end

이 내용이 도움이 되기를 바랍니다!

SOAP 메서드를 호출하기 위해 아래와 같은 HTTP 호출을 사용했습니다.

require 'net/http'

class MyHelper
  def initialize(server, port, username, password)
    @server = server
    @port = port
    @username = username
    @password = password

    puts "Initialised My Helper using #{@server}:#{@port} username=#{@username}"
  end



  def post_job(job_name)

    puts "Posting job #{job_name} to update order service"

    job_xml ="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://test.com/Test/CreateUpdateOrders/1.0\">
    <soapenv:Header/>
    <soapenv:Body>
       <ns:CreateTestUpdateOrdersReq>
          <ContractGroup>ITE2</ContractGroup>
          <ProductID>topo</ProductID>
          <PublicationReference>#{job_name}</PublicationReference>
       </ns:CreateTestUpdateOrdersReq>
    </soapenv:Body>
 </soapenv:Envelope>"

    @http = Net::HTTP.new(@server, @port)
    puts "server: " + @server  + "port  : " + @port
    request = Net::HTTP::Post.new(('/XISOAPAdapter/MessageServlet?/Test/CreateUpdateOrders/1.0'), initheader = {'Content-Type' => 'text/xml'})
    request.basic_auth(@username, @password)
    request.body = job_xml
    response = @http.request(request)

    puts "request was made to server " + @server

    validate_response(response, "post_job_to_pega_updateorder job", '200')

  end



  private 

  def validate_response(response, operation, required_code)
    if response.code != required_code
      raise "#{operation} operation failed. Response was [#{response.inspect} #{response.to_hash.inspect} #{response.body}]"
    end
  end
end

/*
test = MyHelper.new("mysvr.test.test.com","8102","myusername","mypassword")
test.post_job("test_201601281419")
*/

도움이 되길 바랍니다.건배.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top