ruby http爬虫中的 :body 用法问题

本文探讨了使用Ruby的HTTP客户端库发送POST请求时遇到的问题,特别是关于Content-Type设置的影响及如何正确地构造请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

require 'http'
url = 'http://localhost/b.php'
data = 'whoami=whoami'
html = HTTP.via('127.0.0.1',8080).headers('Content-Type'=> 'application/x-www-form-urlencoded').post(url, :body => data)
puts html

 引用perl6 中的 User-agent模块中的一段文本:

Adds the form data, supplied either as a Hash, an Array of Pair,
or in a named parameter style, to the POST request (it doesn't
make sense on most other request types.) The default is to use
'application/x-www-form-urlencoded' and 'multipart/form-data' can be used
by providing the ':multipart' adverb.  Alternatively a previously applied
"content-type" header of either 'application/x-www-form-urlencoded'
or 'multipart/form-data' will be respected and in the latter case any
applied boundary marker will be retained.

 原文出处:

https://github.com/sergot/http-useragent/blob/master/lib/HTTP/Request.pm6

perl6中, http-useragent中的 add-form-data 函数会自动添加如下头:

Content-Type : application/x-www-form-urlencoded

但在 ruby http模块中, 当你发送如下POST数据时:

data = "cmd=whoami"

html = HTTP.post(url, body:data)

原始数据头为:

POST /b.php HTTP/1.1
Connection: close
Host: localhost
User-Agent: http.rb/3.0.0
Content-Length: 13

cmd=whoami

 

些数据并没有 Contype-Type: application/x-www-form-urlencoded 头, 此时虽然发送了数据过去, 但服务端并不会接收到(因为少了Contype-Type:app......这一个header)

如果改用如下代码, Contype-Type: appli..... 头会默认为你加上。

data = {‘cmd’=>'whoami'}

html = HTTP.post(url, form:data)

原始数据包为:

POST /b.php HTTP/1.1
Connection: close
Content-Type: application/x-www-form-urlencoded
Host: localhost
User-Agent: http.rb/3.0.0
Content-Length: 13

cmd=whoami

 

 

form与body的差别是, form为hash类型,  body为字符串型。

为了方使测试, 还是body比起form方便得多。

只是每次使用时, 记得加上:

Content-Type: application/x-www-form-urlencoded

 

示例代码:

require 'http'
url = 'http://localhost/b.php'
data = 'whoami=whoami'
html = HTTP.via('127.0.0.1',8080).headers('Content-Type'=> 'application/x-www-form-urlencoded').post(url, :body => data)
puts html

 

转载于:https://www.cnblogs.com/perl6/p/8045207.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值