如何从PUT请求中获取URL的值?在Ruby中

vc9ivgsu  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(100)

我需要的是PUT请求中URL的值。下面是PUT请求的结果。响应:{"result":{"attempts":1,"url":null}}
我不知道问题出在哪里。

loop do
  response = HTTParty.put("#{API_ENDPOINT}/challenges", headers: { 'X-Challenge-Id' => challenge_id })
  puts "Response: #{response}"

  if response['error']
    puts "Error: #{response['error']}"
  elsif response.key?('result')
    result = response['result']
    attempts = result['attempts']
    url = result['url']
    if attempts.zero?
      puts "Challenge failed. Attempts: #{attempts}"
    elsif url.nil?
      puts "Challenge succeeded but no URL available. Attempts: #{attempts}"
    else
      puts "Challenge succeeded. Attempts: #{attempts}"
      puts "URL with keyword: #{API_ENDPOINT}#{url}"
    end

    break
  end
end

我想做的事情是,通过向/challenges发出POST HTTP请求来启动一个挑战。在响应中的预定调用时间(actives_at),HTTP请求作为PUT发送到/challenges。此时,需要将质询ID(id)给予X-Challenge-Id报头。
我试图打印出错误消息,但似乎挑战成功,只是没有可用的URL。

cgyqldqp

cgyqldqp1#

您需要将JSON从字符串解析为散列

json_response = HTTParty.put("#{API_ENDPOINT}/challenges", headers: { 'X-Challenge-Id' => challenge_id })

response = JSON.parse(json_response.body, symbolize_names: true)

之后,您可以处理响应

if response[:error]
  puts "Error: #{response[:error]}"
elsif response[:result]
  attempts = response[:result][:attempts]
  url = response[:result][:url]

  if attempts.zero?
    puts "Challenge failed. Attempts: #{attempts}"
  elsif url.nil?
    puts "Challenge succeeded but no URL available. Attempts: #{attempts}"
  else
    puts "Challenge succeeded. Attempts: #{attempts}"
    puts "URL with keyword: #{API_ENDPOINT}#{url}"
  end
end

相关问题