ファイルをにアップロードするための簡単なrubyスクリプトがありますTCP接続を介したサーバー/ Webアプリですが、機能しません。スクリプトを実行すると、Webアプリ/サーバー側で何も起こりません。CURLを使用してファイルをアップロードしようとしましたが、アップロードされたため、サーバーは正常に機能します。以下の私のコードで、私が間違っていることを教えてください。私はルビー1.9.2-p290を使用しています。よろしくお願いします。
require "socket"
host = "myapp.herokuapp.com"
port = 80
client = TCPSocket.open(host, port)
client.print("POST /api/binary HTTP/1.1rn")
client.print("Host: myapp.herokuapp.comrn")
client.print ("Accept: */* rn")
client.print ("Content-Type: multipart/form-data;boundary=AaB03x rn")
client.print("n" + "AaB03x"+ "n" "Content-Disposition: form-data; name="datafile"; filename="cam.jpg" n Content-Type: image/jpeg rn")
client.print ("rn")
data = File.open("./pic.jpg", "rb") {|io| io.read}
client.print (data)
client.print ("rn")
client.print("boundary=AaB03xrn")
client.close
IRBコンソール
>require "socket"
=> true
> client = TCPSocket.open("myapp.herokuapp.com", 80)
=> #<TCPSocket:fd 3>
> client.print("GET /api/users HTTP/1.1")
=> nil
> client.print("POST /api/binary HTTP/1.1")
=> nil
回答:
回答№1は1有効なHTTPリクエストを送信していることを確認する必要があります。
あなたには必要だ
Content-Length
ヘッダ。つまり、ヘッダーの長さを決定してからボディを送信できるように、事前にボディを組み立てる必要があります。これを間違えると、サーバーは、来ない入力をさらに読み取ろうとしてブロックしてしまう可能性があります。マルチパート境界を修正する必要があります。彼らはで始まる必要があります
--
、次にヘッダーからのトークン:--AaB03x
。最後のものはで終わる必要があります--
あまりにも:--AaB03x--
。問題を引き起こす可能性のある末尾の空白もヘッダーにないことを確認してください。
リクエストの解析を妨げることはないかもしれませんが、整理する必要があるその他の事項:
ヘッダーの改行は次のようになります
rn
だけでなくn
.ヘッダー行の前に空白を入れないでください。
require "socket"
host = "myapp.herokuapp.com"
port = 80
client = TCPSocket.open(host, port)
# Write out the headers.
client.print("POST /api/binary HTTP/1.1rn")
client.print("Host: myapp.herokuapp.comrn")
client.print ("Accept: */* rn")
# Note: no trailing whitespace.
client.print ("Content-Type: multipart/form-data;boundary=AaB03xrn")
# Assemble the body.
# Note rn for all line endings, body doesn"t start with newline.
# Boundary marker starts with "--".
body = "--AaB03xrn"
body << "Content-Disposition: form-data; name="datafile"; filename="cam.jpg"rn"
# Header starts at left of line, no leading whitespace.
body << "Content-Type: image/jpegrn"
body << "rn"
data = File.open("./pic.jpg", "rb") {|io| io.read}
body << data
body << "rn"
# Final boundary marker has trailing "--"
body << "--AaB03x--rn"
# Now we can write the Content-Length header, since
# we now know the size of the body.
client.print "Content-Length: #{body.bytesize}rn"
# Blank line.
client.print "rn"
# Finally write out the body.
client.print body
# In reality you would want to parse the response from
# the server before closing the socket.
client.close