restClient作为带有cookie的Post方法

时间:2015-11-24 11:39:38

标签: ruby post

我在Ruby工作,我完全是新手。

我需要提供restclient post request以及我的cookies以及标题。

我已经收到了第一次来电的回复,我从该回复中获得了隐藏价值,然后我尝试使用以前生成的标题和Cookie发布请求。

我尝试使用以下代码

    require 'rest_client'

    res = RestClient::Request.execute(
                method: :post, 
                url: 'https://evision-sperf.as.itc.ca/urd/sit?q=&label=Search+UBC&site=*.ubc.ca&%25.WEB_HEAD.MENSYS.1=&%25.DUM_MESSAGE.MENSYS.1=&SCREEN_WIDTH.DUMMY.MENSYS.1=1280&SCREEN_HEIGHT.DUMMY.MENSYS.1=720&%25.DUMMY.MENSYS.1=2015112407571924%1BFC6A057FA9E603F56F47993BD4B50175B30B66E67F252E2BEE51F0B324DF2743AAF2D3373D219887287FFD0EFC1ECE4BD122EDB3AA44D7E7889464863851C9EB%1B0A8A488A92C411E5A4FEF2C9F2BFA664%1BNONE&RUNTIME.DUMMY.MENSYS.1=&PARS.DUMMY.MENSYS.1=&MUA_CODE.DUMMY.MENSYS.1=800564&PASSWORD.DUMMY.MENSYS.1=Ubc123%24&BP101.DUMMY_B.MENSYS.1=Login+%3E%3E',
                headers: {"JSESSIONID"=>"F61C6D1266F4668E7E004A8D0F835C03", "ace-sis-perf-svapps"=>"R2440364609"},                                                   
                cookies: {'JSESSIONID' => 'F61C6D1266F4668E7E004A8D0F835C03', 'ace-sis-perf-svapps' => 'R2440364609'}
             )


    puts res.code

    puts res.to_str

但反应不对,它说错误。

任何人都可以在这里协助如何使用标题和Cookie进行此帖后调用吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

result = RestClient::Request.execute(
            method: :post, 
            url: 'http://localhost/example.json',
            headers: {'X-HEADER' => 'header-value'},                                                   
            cookies: {'cookie-name' => 'value'}
         )

此处有更多详情:https://github.com/rest-client/rest-client#passing-advanced-options

您还可以使用https://httpbin.org/来测试代码。例如:

require 'rest_client'

res = RestClient::Request.execute(
        method: :post,
        url: 'https://httpbin.org/post',
        headers: {"X-HEADER-1"=>"header-value-1", "X-HEADER-2"=>"header-value-2"},
        cookies: {'MY-COOKIE-1' => 'cookie-1-value', 'MY-COOKIE-2' => 'cookie-2-value'}
)

puts res.code
puts res.to_str

会回复你:

200
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*; q=0.5, application/xml", 
    "Accept-Encoding": "gzip, deflate", 
    "Cookie": "MY-COOKIE-1=cookie-1-value;MY-COOKIE-2=cookie-2-value", 
    "Host": "httpbin.org", 
    "User-Agent": "Ruby", 
    "X-Header-1": "header-value-1", 
    "X-Header-2": "header-value-2"
  }, 
  "json": null, 
  "origin": "200.100.100.100", 
  "url": "https://httpbin.org/post"
}

如您所见,代码正确设置了标头和Cookie。