Add option to send non-GET requests with JSON encoding.

Andrew Cantino 10 years ago
parent
commit
eee3a8ef1f
1 changed files with 11 additions and 1 deletions
  1. 11 1
      app/models/agents/post_agent.rb

+ 11 - 1
app/models/agents/post_agent.rb

@@ -11,6 +11,8 @@ module Agents
11 11
 
12 12
       The `method` used can be any of `get`, `post`, `put`, `patch`, and `delete`.
13 13
 
14
+      By default, non-GETs will be sent with form encoding (`application/x-www-form-urlencoded`).  Change `content_type` to `json` to send JSON instead.
15
+
14 16
       The `headers` field is optional.  When present, it should be a hash of headers to send with the request.
15 17
     MD
16 18
 
@@ -20,6 +22,7 @@ module Agents
20 22
       {
21 23
         'post_url' => "http://www.example.com",
22 24
         'expected_receive_period_in_days' => 1,
25
+        'content_type' => 'form',
23 26
         'method' => 'post',
24 27
         'payload' => {
25 28
           'key' => 'value'
@@ -95,7 +98,14 @@ module Agents
95 98
     def post_data(data, request_type = Net::HTTP::Post)
96 99
       uri = generate_uri
97 100
       req = request_type.new(uri.request_uri, headers)
98
-      req.form_data = data
101
+
102
+      if interpolated['content_type'] == 'json'
103
+        req.set_content_type('application/json', 'charset' => 'utf-8')
104
+        req.body = data.to_json
105
+      else
106
+        req.form_data = data
107
+      end
108
+
99 109
       Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == "https") { |http| http.request(req) }
100 110
     end
101 111