Module: JekyllHTTPRequest::Filter

Defined in:
lib/jekyll-http-request/filter.rb

Instance Method Summary collapse

Instance Method Details

#http_request(url, method = "GET", headers = "", body = "") ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jekyll-http-request/filter.rb', line 8

def http_request(url, method = "GET", headers = "", body = "")
  key = url + method + headers + body
  JekyllHTTPRequest.cache.getset(key) do
    Jekyll.logger.debug("requesting %s %s %s %s" % [method, url, headers, body])

    uri = URI(url)

    case method
    when "POST"
      req = Net::HTTP::Post.new(uri)
    when "GET"
      req = Net::HTTP::Get.new(uri)
    else
      raise ScriptError.new("unsupported method: should be POST or GET got " + method)
    end

    # add headers
    if headers
      headers.split("|").each do |header|
        key, value = header.split(":")
        req[key] = value
      end
    end

    # add body
    if body
      req.body = body
    end

    # check is https
    isHTTPS = url.index("https") == 0

    # do request
    res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => isHTTPS) { |http|
      http.request(req)
    }

    # return response body and force encoding UTF-8
    return res.body.force_encoding("UTF-8")
  end
end