尝试在 Ruby 中复制移动应用程序 POST 请求,出现 502 网关错误

Posted

技术标签:

【中文标题】尝试在 Ruby 中复制移动应用程序 POST 请求,出现 502 网关错误【英文标题】:Trying to replicate Mobile App POST Request in Ruby, Getting 502 Gateway Error 【发布时间】:2019-07-06 23:12:38 【问题描述】:

我正在尝试自动化我可以使用 Ruby 在 iPhone 应用程序中手动执行的操作,但是当我这样做时,我收到 502 bad gateway 错误。

使用 Charles Proxy 我收到了 iPhone 应用发出的请求:

POST /1.1/user/-/friends/invitations HTTP/1.1
Host: redacted.com
Accept-Locale: en_US
Accept: */*
Authorization: Bearer REDACTED
Content-Encoding: gzip
Accept-Encoding: br, gzip, deflate
Accept-Language: en_US
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 66
Connection: keep-alive
X-App-Version: 814

invitedUserId=REDACTED&source=PROFILE_INVITATION

我用 Ruby 编写了以下代码来发送同样的请求:

@header_post = 
  "Host" => "redacted.com",
  "Accept-Locale" => "en_US",
  "Accept" => "*/*",
  "Authorization" => "Bearer REDACTED",
  "Content-Encoding" => "gzip",
  "Accept-Encoding" => "br, gzip, deflate",
  "Accept-Language" => "en_US",
  "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
  "Connection" => "keep-alive",
  "X-App-Version" => "814"

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
path = '/1.1/user/-/friends/invitations'

data = "invitedUserId=REDACTED&source=PROFILE_INVITATION"

resp, data = http.post(path, data, @header_post)

不幸的是,我在运行此代码时收到 502 Bad Gateway Error。

我注意到的一件事是我认为这里解决方案的关键是,在移动应用程序发出的 POST 请求中,内容长度为 66。但字符串“invitedUserId=REDACTED&source=PROFILE_INVITATION”的长度为 un - 编辑后的 ​​userId 仅为 46。

我是否缺少另一个格式为“&param=value”且长度为 20 的表单变量?还是我错过了什么?

提前谢谢你!

【问题讨论】:

让您的生活更轻松。使用 HTTParty,就像大多数 ruby​​ists 一样:github.com/jnunemaker/httparty 【参考方案1】:

这可能与您发送的正文长度没有直接关系。

我在这里看到可能有 2 个问题:

502 错误:您的uri.hostport 是否正确? 502 错误意味着服务器端有问题。也可以尝试删除 Host 标头。 正文内容未压缩

您正在定义一个标头 Content-Encoding: gzip,但您没有压缩数据(Net::Http 不会自动执行此操作)。

尝试类似的东西:

require "gzip"

@header_post =  
  # ... 


http = Net::HTTP.new(uri.host, uri.port)
path = '/1.1/user/-/friends/invitations'

data = "invitedUserId=REDACTED&source=PROFILE_INVITATION"

# instanciate a new gzip buffer
gzip = Zlib::GzipWriter.new(StringIO.new)

# append your data
gzip << data

# get the gzip body and use it in your request
body = gzip.close.string
resp, data = http.post(path, body, @header_post)

或者,服务器可能正在接受非压缩内容。您可以尝试删除Content-Encoding 原始代码中的错误。

但是,如果这是唯一的错误,服务器不应发送 502 而是 4xx 错误。所以我猜想上面建议的uri配置还有另一个问题。

【讨论】:

以上是关于尝试在 Ruby 中复制移动应用程序 POST 请求,出现 502 网关错误的主要内容,如果未能解决你的问题,请参考以下文章

ruby [Jekyll补充数据模块]将jekyll post的补充数据文件复制到帖子的内置html附近的位置#data #jekyll

在Ruby中发送HTTP / 2 POST请求

使用与移动设备相同的 API 开发网站

如何在Angularjs中调用post方法? [复制]

查尔斯请求“文本”选项卡

请建议适当的附件插件/宝石用于 Rails 2.0.2 和 Ruby 1.8.7