###

alias hbin me

Handle 301 Redirection in Ruby

While I send a GET request to some URI, I got a 301 MOVED PERMANENTLY response returned.

Here is the code:

1
2
require 'net/http'
response = Net::HTTP.get_response(URI(http://***/xyz))

The response’s status code is 301 and body is a empty string.

Solution

  • Use open-uri, open-uri handles redirects automatically.
1
2
require 'open-uri'
response = open('http://***/xyz')
  • Handle redirects with Net::HTTP
1
2
3
4
5
6
7
def get_response_with_redirect(uri)
   r = Net::HTTP.get_response(uri)
   if r.code == "301"
     r = Net::HTTP.get_response(URI.parse(r.header['location']))
   end
   r
end
  • Use the correct URI

The reason that the URI returns a 301 redirection is the trailing slashes are misused. Historically, it’s common for URLs with a trailing slash to indicate a directory, and those without a trailing slash to denote a file:

1
2
http://example.com/foo/ (with trailing slash, conventionally a directory)
http://example.com/foo  (without trailing slash, conventionally a file)

References:

  1. http://stackoverflow.com/questions/7210232/ruby-nethttp-following-301-redirects
  2. http://stackoverflow.com/questions/5948659/trailing-slash-in-urls-which-style-is-preferred

Comments