Techioz Blog

HTTParty POST でファイルを送信するときに Content-Length ヘッダーと Content-Type ヘッダーを設定するにはどうすればよいですか?

概要

ヘッダーを次のように設定しています。 ファイルは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 がチャンクに設定されます。

Content-Length、Content-Type、および Transfer-Encoding を設定し、HTTParty がそれらを独自に設定することを回避するにはどうすればよいでしょうか?

それが明らかだといいのですが。

よろしくお願いします!

解決策

これを試して

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