본문 바로가기
2014.03.14 18:40

HTTP Posts in Ruby

조회 수 1666 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

https://coderwall.com/p/c-mu-a


Sometimes I need to make simple HTTP posts in a Ruby script. Using a 3rd party library may be too clunky for such a simple script.


This post helps a lot, but it doesn't cover all my needs. Specifically, when working with the Switchvox API, the API methods are expected to be a JSON parameter.


Let's start by imply posting some JSON.


Post some JSON

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse("http://localhost:3000/users")

header = {'Content-Type': 'text/json'}
user = {user: {
                   name: 'Bob',
                   email: 'bob@example.com'
                      }
            }

# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = user.to_json

# Send the request
response = http.request(request)


This will simply submit a POST request with the JSON as the body.


But, there were some methods that required a file be submitted with the JSON? Things get a little more complicated when you do this, but it is still manageable.


Post a file with some JSON

require 'net/http'
require 'uri'
require 'json'
require 'mime/types'

uri = URI.parse("http://localhost:3000/users")
BOUNDARY = "AaB03x"

header = {"Content-Type": "multipart/form-data, boundary=#{BOUNDARY}"}
user = {user: {
                   name: 'Bob',
                   email: 'bob@example.com'
                      }
            }
file = "test_file.xml"

# We're going to compile all the parts of the body into an array, then join them into one single string
# This method reads the given file into memory all at once, thus it might not work well for large files
post_body = []

# Add the file Data
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"user[][image]\"; filename=\"#{File.bsename(file)}\"\r\n"
post_body << "Content-Type: #{MIME::Types.type_for(file)}\r\n\r\n"
post_body << File.read(file)

# Add the JSON
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"user[]\"\r\n\r\n"
post_body << user.to_json
post_body << "\r\n\r\n--#{BOUNDARY}--\r\n"

# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = post_body.join

# Send the request
response = http.request(request)


And there you have it! A multipart HTTP Post in Ruby without an external library. You can probably see how you could add multiple files and sets JSON objects.


Is it worth not using a 3rd party library and doing it yourself?




Title
List of Articles
번호 제목 글쓴이 날짜 조회 수
31 Different Ways to Set Attributes in ActiveRecord (attribute, create, update, validation) Hojung 2015.05.24 1271
30 Ruby Style Guide Hojung 2015.02.05 1610
29 Refresh content automatically after some period time on Rails Hojung 2015.01.22 2214
28 Install ruby-filemagic on Mac (brew, libmagic) Hojung 2014.12.03 1476
27 Byte manipulation in Ruby Hojung 2014.12.03 1436
26 How to use Github for your project file Hojung 2014.09.24 1053
25 Ruby map, each, collect, inject, reject, select quick reference Hojung 2014.06.10 1815
24 Difference between collect, select, map and each in ruby Hojung 2014.06.10 1298
23 remove nil from array (compact, compact!) Hojung 2014.06.10 1605
22 remove child association model when parent removed (rails-dependent-destroy) Hojung 2014.06.03 1662
21 deploying cron jobs with whenever gem Hojung 2014.06.01 1703
20 Get list of a class' instance methods Hojung 2014.06.01 1366
19 Optional method parameters in Ruby Hojung 2014.05.29 1487
18 Best Ruby On Rails Content Management Systems (CMS) Hojung 2014.04.26 2683
17 The simple way to print exceptions in Ruby Hojung 2014.04.07 1518
16 Ruby Symbols Hojung 2014.04.05 6291
15 What is the difference between a Symbol and String? Hojung 2014.04.05 1493
14 install Rbenv, ruby and rails Hojung 2014.03.22 1672
» HTTP Posts in Ruby Hojung 2014.03.14 1666
12 optparse: mandatory and optional arguments example Hojung 2014.03.14 2353
Board Pagination ‹ Prev 1 2 Next ›
/ 2

Designed by sketchbooks.co.kr / sketchbook5 board skin

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5