如何从Ruby发出HTTP POST请求

时间:2017-04-27 18:41:53

标签: ruby http request http-post

我之前从未在Ruby中做过POST,而且我错过了一些简单的东西。

我正在尝试提出此请求:

curl -s -X POST "http://example.com:8280/purest/chatbot/actions/message" --data "message=hello there&rooms=myroom"

我有:

    url = "http://example.com:8280"
    uri = URI.parse(url)

    http = Net::HTTP.new(uri.host, uri.port)
    http.set_debug_output($stdout)

    request = Net::HTTP::Post.new("/purest/chatbot/actions/message")
    request.body = "message=hey from me in ruby&rooms=myroom"

    response = http.request(request)

这是输出:

<- "POST /purest/chatbot/actions/message HTTP/1.1\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: example.com:8280\r\nContent-Length: 60\r\n\r\n"
<- "message=hey from except now from ruby&rooms=myroom"
-> "HTTP/1.1 400 Bad Request\r\n"
-> "Server: nginx\r\n"
-> "Date: Thu, 27 Apr 2017 18:33:33 GMT\r\n"
-> "Content-Type: application/json; charset=utf-8\r\n"
-> "Transfer-Encoding: chunked\r\n"
-> "Connection: close\r\n"
-> "Content-Language: en-US\r\n"
-> "Session-Id: \r\n"
-> "Cache-Control: no-cache\r\n"
-> "X-Moawsl-Info: php_pid=52478;php_tte_ms=14.93;php_hit=250;php_cpu_ms=15.02;maxrss=223016;customer_id=;session_order_id=;\r\n"
-> "Server_Id: bo1.200.21\r\n"
-> "TXID: CuDIFVkCOX1KINAaSrUgAg==\r\n"
-> "\r\n"
-> "64\r\n"
reading 100 bytes...
-> "[{\"code\":400,\"message\":\"Bad Request: Content-Type not supported: \"}]Encoding type  is not supported."
read 100 bytes
reading 2 bytes...
-> "\r\n"
read 2 bytes
-> "0\r\n"
-> "\r\n"
Conn close
#<Net::HTTPBadRequest 400 Bad Request readbody=true>

有人能帮助我吗?

0 个答案:

没有答案