| 1 |
require 'httpclient' |
| 2 |
require 'json' |
| 3 |
|
| 4 |
module HTTP |
| 5 |
class Message |
| 6 |
# Returns JSON object of message body |
| 7 |
alias original_content content |
| 8 |
def content |
| 9 |
if JSONClient::CONTENT_TYPE_JSON_REGEX =~ content_type |
| 10 |
JSON.parse(original_content) |
| 11 |
else |
| 12 |
original_content |
| 13 |
end |
| 14 |
end |
| 15 |
end |
| 16 |
end |
| 17 |
|
| 18 |
|
| 19 |
# JSONClient provides JSON related methods in addition to HTTPClient. |
| 20 |
class JSONClient < HTTPClient |
| 21 |
CONTENT_TYPE_JSON_REGEX = /(application|text)\/(x-)?json/i |
| 22 |
|
| 23 |
attr_accessor :content_type_json |
| 24 |
|
| 25 |
class JSONRequestHeaderFilter |
| 26 |
attr_accessor :replace |
| 27 |
|
| 28 |
def initialize(client) |
| 29 |
@client = client |
| 30 |
@replace = false |
| 31 |
end |
| 32 |
|
| 33 |
def filter_request(req) |
| 34 |
req.header['content-type'] = @client.content_type_json if @replace |
| 35 |
end |
| 36 |
|
| 37 |
def filter_response(req, res) |
| 38 |
@replace = false |
| 39 |
end |
| 40 |
end |
| 41 |
|
| 42 |
def initialize(*args) |
| 43 |
super |
| 44 |
@header_filter = JSONRequestHeaderFilter.new(self) |
| 45 |
@request_filter << @header_filter |
| 46 |
@content_type_json = 'application/json; charset=utf-8' |
| 47 |
end |
| 48 |
|
| 49 |
def post(uri, *args, &block) |
| 50 |
@header_filter.replace = true |
| 51 |
request(:post, uri, jsonify(argument_to_hash(args, :body, :header, :follow_redirect)), &block) |
| 52 |
end |
| 53 |
|
| 54 |
def put(uri, *args, &block) |
| 55 |
@header_filter.replace = true |
| 56 |
request(:put, uri, jsonify(argument_to_hash(args, :body, :header)), &block) |
| 57 |
end |
| 58 |
|
| 59 |
private |
| 60 |
|
| 61 |
def jsonify(hash) |
| 62 |
if hash[:body] && hash[:body].is_a?(Hash) |
| 63 |
hash[:body] = JSON.generate(hash[:body]) |
| 64 |
end |
| 65 |
hash |
| 66 |
end |
| 67 |
end |