How to Fix Net::HTTPBadResponse: wrong status line: “” in Ruby


Why  This Happens:

Net::HTTPBadResponse – wrong status line: “{“:
Argument 1
This came about because an example for an HTTP GET in the Ruby standard documentation doesn’t mention HTTPS, and it is only natural that at some point you’ll try to use that same code to get something via SSL/HTTPS, and it will fail with a similar error to the above.
Solution

 http.use_ssl = (url.scheme == 'https')

Argument 2
There is encoding required for special characters in URI.
Solution

URI.encode

Timeout Error Occurs
Solution

 http.read_timeout = 1000

::Complete Solution::

  # Enhanced version of reference bascially taken from http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html then modified to support SSL

  def self.fetch(uri_str,address ,limit = 10)
    # You should choose better exception.
    raise ArgumentError, 'HTTP redirect too deep' if limit == 0
    uri_str = URI.encode(uri_str + "?address=#{address.gsub(' ', '+')}&sensor=false")
    url = URI.parse(uri_str)
    http = Net::HTTP.new(url.host, url.port)
    http.read_timeout = 1000
    http.use_ssl = (url.scheme == 'https')
    request = Net::HTTP::Get.new(uri_str)
    response = http.start {|http| http.request(request) }
    case response
    when Net::HTTPSuccess
      response.body
    when Net::HTTPRedirection
      fetch(response['location'], limit - 1)
    else
      response.error!
    end
  end

Note
In above fetch method:
parameters:
uri_str=base_uri
address=address parameter’s data and other query string parameters
Useage:
This method is used to fetch lat-long from google api on the basis of address.

Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: , ,
Posted in APIs, Ruby Little Codes, Ruby on Rails
3 comments on “How to Fix Net::HTTPBadResponse: wrong status line: “” in Ruby
  1. I was having another issue:

    wrong status line: “”

    But your tip solve my problem, thanks! If you can, edit the post and tell your users this works for cases like my too.

    Really thanks!
    Fernando Paladini.
    http://www.btc-stores.com

  2. taimoor.changaiz says:

    Thanks Fernando. Its my pleasure that my post helped you, so what issue you faced? and what is your suggested status line ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

StackOverFlow
Categories
Archives
%d bloggers like this: