1

我的目标是解决 PUT 操作中的“丢失更新问题”(参见http://www.w3.org/1999/04/Editing/)。我正在使用 sinatra,作为客户端,我使用 rest_client。我如何检查它是否有效?我的客户总是返回 200 代码。我是否使用正确调用它的参数?(PUT 本身有效)

西纳特拉代码:

put '/players/:id' do |id|
    etag 'something'
    if Player[id].nil? then
        halt 404
    end
    begin
        data = JSON.parse(params[:data])
        pl = Player[id]
        pl.name = data['name']
        pl.position = data['position']
        if pl.save
            "Resource modified."
        else
            status 412
            redirect '/players'   
        end

    rescue Sequel::DatabaseError   
        409 #Conflict - The request was unsuccessful due to a conflict in the state of the resource.
    rescue Exception => e 
        400
        puts e.message   
    end
end

客户端调用:

player = {"name" => "John Smith", "position" => "def"}.to_json

RestClient.put('http://localhost:4567/players/1', {:data => player, :content_type => :json, :if_none_match => '"something"'}){ |response, request, result, &block|
    p response.code.to_s + " " + response
}

我已经尝试过输入:if_none_match =>“某事”,我尝试过:if_match。没有什么变化。如何将标头放入 RestClient 请求?如何获得不同于 200 的状态?(即 304 未修改)?

4

1 回答 1

0

您的有效负载和标头位于相同的哈希中。RestClient您必须在第二个哈希中指定标题。尝试:

player = {"name" => "John Smith", "position" => "def"}.to_json
headers = {:content_type => :json, :if_none_match => '"something"'}

RestClient.put('http://localhost:4567/players/1', {:data => player}, headers) do |response, request, result, &block|
    p response.code.to_s + " " + response
end

我不确定是否RestClient正确翻译了标题。如果上述方法不起作用,请尝试:

headers = {'Content-Type' => :json, 'If-None-Match' => '"something"'}
于 2011-10-19T11:22:12.047 回答