在set_form_data POST中转义参数

时间:2011-08-01 20:00:53

标签: ruby http-post net-http

这是最奇怪的事情。当我在;中添加set_form_data时,value在服务器端被解释为value;。当我删除;时,'dontescape'的值被解释为file%3a%2f%2f%2fpath%2fto。到底发生了什么?除非我明确地调用CGI :: escape,否则我不想要任何转义!请帮助:)

postParams = {
  'key1' => 'value',
  'dontescape' => 'file:///path/to'
}

url = URI.parse('https://my.url')

req = Net::HTTP::Post.new(url.path)
req.basic_auth('username', 'password')

req.set_form_data(postParams, ';')

sock = Net::HTTP.new(url.host, 443)
sock.use_ssl = true
sock.ssl_version = 'SSLv3'
sock.start do |http|
response = http.request(req) do
  return response.body
end

1 个答案:

答案 0 :(得分:0)

这种情况发生并不好:PHP,Java,Node - 他们都没有这样做 首先,我覆盖:

# Module to override
module Net
    module HTTPHeader   
        def postUrlBuilder(postParams)
            @queryUrl = ''
            if (postParams.nil? or postParams == 0)
                # Null or empty item
            else
                count = 0
                postParams.each_pair do |key,value|
                    if (count == 0)
                        @queryUrl = @queryUrl + key + '=' + value
                        count = count + 1
                    else 
                        @queryUrl = @queryUrl + '&' + key + '=' + value
                    end
                end
            end
            return @queryUrl
        end

        def set_form_data(postParams, sep = '&')
            self.body = postUrlBuilder(postParams)
            self.content_type = 'application/x-www-form-urlencoded'
        end
        alias form_data= set_form_data
   end
end

然后我写了自己的帖子方法:

def monkey_patch_post_request(postParams)
        url = URI.parse(@monkeyPatchUrl)    
        req = Net::HTTP::Post.new(url.path)
        req.basic_auth @companyId, @apiKey
        req.set_form_data(postParams, sep = '&')
        sock = Net::HTTP.new(url.host, 443)
        sock.use_ssl = true
        sock.ssl_version='SSLv3'
        sock.start do |http|
            response = http.request(req)
            return response.body
        end
    end

这应该有帮助!