这是这篇文章的最后一次尝试:
当我尝试在线程中使用rest-client进行调用时,它会失败并提前离开线程。当我在线程之外运行它时,它是正常的。
有什么想法吗?
require 'base64'
require 'json'
require 'rest-client'
require 'thwait'
test = Thread.new {
endpoint = "http://my/url"
headers = {'Authorization' => "Basic #{Base64.encode64("username:password")}", 'Accept' => 'Application/json', 'Content-Type' => 'Application/json'}
payload = JSON.parse("{\"documents\": { \"textField1\":\"asdf\" }}").to_json
# See the results of the above. Successful now (headers hash with expected encoded value, JSON string as expected)
puts headers
puts payload
# Expecting REST response on the console. Nothing appears on the console.
puts RestClient::Request.execute(:method => :post, :url => endpoint, :headers => headers, :payload => payload, :verify_ssl => false)
# Expecting simple text output to the console to see if execution reaches this point. Nothing appears on the console.
puts 'done'
}
# Where this is actually being used, ThreadsWait is used for thread management, so simulating that here
thwait = ThreadsWait.new(test)
thwait.next_wait发布于 2019-01-04 05:33:08
您需要对线程执行join操作才能看到输出。如果你没有在主线程终止之前加入它,那么它将杀死它(see docs)。
require 'rest-client'
endpoint = "/my/url"
headers = {'Authorization' => "Basic #{Base64.encode64("mycreds")}", 'Accept' => 'Application/json', 'Content-Type' => 'Application/json'}
payload = JSON.parse("{\"documents\": { \"textField1\":\"asdf\" }}").to_json
test_thread = Thread.new {
response = RestClient::Request.execute(:method => :post, :url => endpoint, :headers => headers, :payload => payload, :verify_ssl => false)
puts response
}.join发布于 2019-11-23 08:14:57
我在Ruby 2.5.7和rest-client版本2.0.2中遇到过这个问题。在我升级到rest-client版本2.1.0之后,这个问题就消失了。旧版本的rest-client在Ruby 2.3.1上运行良好。
https://stackoverflow.com/questions/54029115
复制相似问题