HTTParty错误400:简单GET请求上的标头名称无效

时间:2015-07-29 14:25:42

标签: ruby-on-rails http azure get httparty

尽管它相对简单,但我的大脑能够很容易地理解新的概念,所以我在这里。

我正在使用HTTParty与Microsoft Azure API进行交互。以下是他们的GET应该如何显示的示例:

GET https://api.datamarket.azure.com/data.ashx/amla/text-analytics/v1/GetSentiment?Text=hello+world

这里是他们要求包含的标题:

Authorization: Basic <creds>
Accept: application/json

Where <creds> = ConvertToBase64(“AccountKey:” + yourActualAccountKey);  

这是我的HTTParty课程:

  def self.sentiment(phrase)
    require 'base64'
    key = "MYKEYWASHERE"
    accountKey = Base64.encode64("AccountKey:" + key)
    response = get("https://api.datamarket.azure.com/data.ashx/amla/text-analytics/v1/GetSentiment?Text=hello+world", :headers => { "Authorization" => "Basic " + accountKey, "Accept" => "application/json"})
    if response
        return response
    end
  end

它回应:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> <HTML><HEAD><TITLE>Bad Request</TITLE> <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD> <BODY><h2>Bad Request - Invalid Header</h2> <hr><p>HTTP Error 400. The request has an invalid header name.</p> </BODY></HTML>

我也调试了它,它打印出以下内容:

opening connection to api.datamarket.azure.com:443...
opened
starting SSL for api.datamarket.azure.com:443...
SSL established
<- "GET /data.ashx/amla/text-analytics/v1/GetSentiment?Text=hello+world HTTP/1.1\r\nAuthorization: Basic QWNj(...)VREUmk1aWdudXRtL2VN\nak(...)R\r\nAccept: application/json\r\nConnection: close\r\nHost: api.datamarket.azure.com\r\n\r\n"

有什么明显的我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

您在base64编码的基本授权标头中有一个奇怪的\n字符。我真的不知道Base64.encode64()如何生成一个LF字符,你应该调查一下。这会破坏HTTp查询(您在LF(ak(...))字符后面有一个从\n开始的新标题。

但是也要注意不要使用真正的base64编码密钥在堆栈溢出问题中打印调试信息,这种编码只是一个编码,在您将其重新编码为任何字符集,因此您的API密钥是公开的。如果您可以重新询问API密钥。

编辑在堆栈overflo上已经知道ruby base64编码\n错误,有关在60个字符后添加的\n的详细信息,请参阅this answer