【问题标题】:How to set Content-Length and Content-Type headers when sending a file with a HTTParty POST?使用 HTTParty POST 发送文件时如何设置 Content-Length 和 Content-Type 标头?
【发布时间】:2016-08-21 23:15:55
【问题描述】:

我正在设置这样的标题: 其中文件是 test.txt

size = File.size(file)

h = {
  "Content-Type":      'text/plain'
  "Content-Length":     size.to_s,
  "Other-Header":      'some-header'     
 }

b = File.read(file)

HTTParty.post('/some/api/url', {headers: h , body: b})

请求标头设置如下:

<- "POST /some/api/url\r\n
Content-Type: text/plain\r\n  
Content-Length: 16\r\n
Other-Header: some-header\r\n
Connection: close\r\n
Host: somehost.com\r\n
Content-Length: 16\r\n
Content-Type: application/x-www-form-urlencoded\r\n\r\n"

Content-Length 和 Content-Type 被添加和复制,除了 Transfer-Encoding 被设置为 chunked。

如何设置 Content-Length、Content-Type 和 Transfer-Encoding 并避免 HTTParty 自行设置?

希望清楚。

感谢您的宝贵时间!

【问题讨论】:

  • 您尝试通过自己设置这些标头来达到什么目的?
  • 我正在尝试使用 Backblaze.com api 上传文件。他们的文件要求这样。那里的“原始” net/http 中有一个可行的解决方案。我可以使用它,但我想使用 httparty。 backblaze.com/b2/docs/b2_upload_file.html

标签: ruby http-headers content-type httparty content-length


【解决方案1】:

试试这个

HTTParty.post(END_POINT_URL, 
:body => data.to_json,
:headers => { 'Content-Type' => 'application/json', 
'Content-Length' => content_length, 'Other-Header' => other_header, } )    

【讨论】:

  • 谢谢你的答案。但我需要设置内容类型“文本/纯文本”并按原样发送正文,而不是 JSON。我正在将文件上传到 backblaze:(backblaze.com/b2/docs/b2_upload_file.html)。传输编码设置为分块,我需要避免它。
猜你喜欢
  • 2011-04-25
  • 2022-06-10
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 2013-07-22
  • 2015-10-22
相关资源
最近更新 更多