如何解决基于php版本在ruby上创建发布请求
我离开Ruby一段时间了...现在,我需要在ruby上重新创建一个php api连接(curl),以将其添加到我的rails应用程序中,但是我得到的只是一个Net :: HTTPMovedPermanently消息
这是原始的php版本:
$url = "https://marketplace.walmartapis.com/v3/token";
$uniqid = uniqid();
$authorization_key = base64_encode($client_id.":".$client_secret);
$code = "";
$ch = curl_init();
$options = array(
"WM_SVC.NAME: Walmart Marketplace","WM_QOS.CORRELATION_ID: $uniqid","Authorization: Basic $authorization_key","Accept: application/json","Content-Type: application/x-www-form-urlencoded",),);
curl_setopt_array($ch,$options);
$response = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if($code == 201 || $code == 200)
{
$token = json_decode($response,true);
return $token['access_token'];
}
}
这是到目前为止我的Ruby版本:
require 'net/http'
require 'base64'
client_id = "id"
client_secret = "secret"
url = "https://marketplace.walmartapis.com/v3/token/"
uniqid = "1234567890abc"
uri = URI(url)
request = Net::HTTP::Post.new(uri)
request['WM_SVC.NAME'] = 'Walmart Marketplace'
request['WM_QOS.CORRELATION_ID'] = uniqid
request.basic_auth(client_id,client_secret)
request['Accept'] = 'application/json'
request['Content-Type'] = 'application/x-www-form-urlencoded'
http = Net::HTTP.new(uri.host)
response = http.request(request)
puts response
我还缺少什么?
更新...
我已更改了一些基于curl-to-ruby web的内容,并在后面...现在我遇到了400错误
require 'net/http'
require 'uri'
client_id = "foo"
client_secret = "bar"
url = "https://marketplace.walmartapis.com/v3/token"
uniqid = "1234567890abc"
uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request["WM_SVC.NAME"] = "Walmart Marketplace"
request["WM_QOS.CORRELATION_ID"] = uniqid
request.basic_auth(client_id,client_secret)
request["Accept"] = "application/json"
request.content_type = "application/x-www-form-urlencoded"
req_options = {
use_ssl: uri.scheme == "https",}
response = Net::HTTP.start(uri.hostname,req_options) do |http|
http.request(request)
end
puts response.code
puts response.body
我创建了一个新问题,以弄清到目前为止的工作原理,以及与php相比缺少的字段
解决方法
您尝试访问的资源似乎已被移动。 HTTPMovedPermanently响应是HTTPRedirection的一种形式。您的代码应向新位置再次发出请求。
这是直接来自Net :: HTTP文档的示例:
def fetch(uri_str,limit = 10)
# You should choose a better exception.
raise ArgumentError,'too many HTTP redirects' if limit == 0
response = Net::HTTP.get_response(URI(uri_str))
case response
when Net::HTTPSuccess then
response
when Net::HTTPRedirection then
location = response['location']
warn "redirected to #{location}"
fetch(location,limit - 1)
else
response.value
end
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。