Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API call using Net::HTTP throwing Net::HTTPBadResponse error

I am working on rails environment. I am using Net::HTTP module for calling an external API and getting the response. This is working fine in my local host. But in staging it throwing an Net::HTTPBadResponse error. My staging is SSL enabled. This is the difference. Providing the code snippet and error below.

parameters = {'VirtualNumber' => '09845xxxxxx','Number[]' => "09878xxxxxx" }
x = Net::HTTP.post_form(URI.parse("https://example.com"), parameters)

Error:
Net::HTTPBadResponse (wrong status line: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">")

The successful result will be in XML format. Can any one help me to solve this.

Thank You,
Regards

like image 669
apr Avatar asked Nov 02 '22 00:11

apr


1 Answers

The issue was calling the API from ssl enabled site. So while calling the API we need to enable the ssl. And along with that need to provide basic authentication.

parameters = {'VirtualNumber' => '09845xxxxxx','Number[]' => "09878xxxxxx" }
url = URI.parse("https://example.com")
request = Net::HTTP::Post.new(url.path)
request.basic_auth "user", "pass"
request.set_form_data(parameters)
sock = Net::HTTP.new(url.host, url.port)
if url.scheme == 'https'
  sock.use_ssl = true
end
response = sock.start {|http| http.request(request) }
like image 154
apr Avatar answered Nov 08 '22 04:11

apr