【问题标题】:Simple POST request failing with em-http-request简单的 POST 请求因 em-http-request 失败
【发布时间】:2026-01-09 09:55:02
【问题描述】:

以下查询适用于requestmaker

URI:

http://www.cleverbot.com/webservicemin/

查询:

start=y&icognoid=wsf&fno=0&sub=Say&islearning=1&cleanslate=false&stimulus=!!!%20there%20was%20an%20error%20!!!&icognocheck=af71393ce00d9126a247df2f53948e79

但它不适用于em-http-request

require 'eventmachine'
require 'em-http-request'


uri  = 'http://www.cleverbot.com/webservicemin/'
query = 'start=y&icognoid=wsf&fno=0&sub=Say&islearning=1&cleanslate=false&stimulus=!!!%20there%20was%20an%20error%20!!!&icognocheck=af71393ce00d9126a247df2f53948e79'

EM.run do

  http = EM::HttpRequest.new(uri).post(query: query)
  http.callback { puts http.response; EM.stop }
  http.errback { puts 'There was an error'; EM.stop }
end

打印There was an error。我感到很困惑,因为这个简单的示例适用于任何其他发送请求的方法,并且我检查了我的用法是否有误,但似乎没有。

编辑:仅供参考,这不是使用cleverbot的正确方法。通过在:query 下发送数据,我犯了第二个错误。如果您使用http.post(body: query),它将起作用

【问题讨论】:

  • 您收到的是http.error == "connection closed by server"。这可能是因为错误的query- 它可能与 eventmachine 无关
  • 我尝试直接发布您的查询-cleverbot 回复并注明:curl --data 'start=y&icognoid=wsf&fno=0&sub=Say&islearning=1&cleanslate=false&stimulus=!!!%20there%20was%20an%20error%20!!!&icognocheck=af71393ce00d9126a247df2f53948e79' http://www.cleverbot.com/webservicemin/
  • @Grych 这很奇怪,我将它粘贴到 sh 中并得到了一个有效的答案(cleverbot 出于某种原因使用\r 分隔它的行,也许这就是你什么都没看到的原因?)
  • 是的,对,这是奇怪的反应 :) 也许这是 HttpRequest 发现它是 connection closed by server 的原因

标签: ruby http eventmachine em-http-request


【解决方案1】:

看起来像一个糟糕实现的服务器:它中止 TCP 连接而没有返回正确的 HTTP 状态代码,这就是为什么您在查询 http.error 时看到“连接被服务器关闭”的原因。

如果将默认用户代理更改为 curl 的 UA 字符串,则会收到响应:

  http = EM::HttpRequest.new(uri).post({
   :query => query,
   :head => {'User-Agent' => 'curl/7.30.0'}
  })

【讨论】: