em-http-request icon indicating copy to clipboard operation
em-http-request copied to clipboard

Add examples for POST request with custom headers

Open Eyal-Shalev opened this issue 6 years ago • 1 comments

Eyal-Shalev avatar May 17 '18 06:05 Eyal-Shalev

In my case i wanted to do a post request with a json body but i was experiencing some issues becase the HttpClient was handling the body as it would have been a form input. I fixed the issue with by overriding ( in my code ) the behavior for the HttpClient#form_encode_body.

module EventMachine
  class HttpClient
    # We need to override the bohavior of the gem class, where a hash is considered a form
    # and not flexibility is given to deal with json body.
    # Please visit https://github.com/igrigorik/em-http-request
    # The issue is at https://github.com/igrigorik/em-http-request/blob/master/lib/em-http/http_encoding.rb#L89
    def form_encode_body(body)
      body.to_json
    end
  end
end

Also i set the headers for application/json in the adapter where the request is done.

class Adapter
    HEADERS = {
      'content-type' => 'application/json',
      'accept' => 'application/json'
    }

  def send_request(post_url, body)
    ....
    conn = EventMachine::HttpRequest.new(post_url)
    conn.use EventMachine::Middleware::JSONResponse

    response = conn.post(head: HEADERS, body: body)
    ...
  end
end

Maybe we would like to make the gem able to deal with this case scenario ?

nic-lan avatar Aug 07 '18 21:08 nic-lan