【问题标题】:HTTP POST contents in HaskellHaskell 中的 HTTP POST 内容
【发布时间】:2010-06-20 05:06:10
【问题描述】:

我正在尝试将一些数据发布到 Haskell 中的服务器,但服务器端出现空置。

我正在为请求使用 Network.HTTP 库。

module Main (main) where

import Network.URI (URI (..), parseURI, uriScheme, uriPath, uriQuery, uriFragment)
import Network.HTTP
import Network.TCP as TCP

main = do
         conn <- TCP.openStream "localhost" 80
         rawResponse <- sendHTTP conn updateTest
         body <- getResponseBody rawResponse
         if body == rqBody updateTest
           then print "test passed"
           else print (body ++ " != " ++ (rqBody updateTest))

updateURI = case parseURI "http://localhost/test.php" of
                  Just u -> u

updateTest = Request { rqURI = updateURI :: URI
                     , rqMethod = POST :: RequestMethod
                     , rqHeaders = [ Header HdrContentType   "text/plain; charset=utf-8"
                                   ] :: [Header]
                     , rqBody = "Test string"
                     }

这个测试从服务器返回空字符串作为响应正文,当我认为它应该回显“测试字符串”帖子时。

理想情况下,我希望复制以下功能:

curl http://localhost/test.php -d 'Test string' -H 'Content-type:text/plain; charset=utf-8'

并正在使用服务器端 test.php 验证结果:

<?php
print (@file_get_contents('php://input'));

我做错了还是应该尝试另一个库?

【问题讨论】:

  • 我建议尝试使用“wireshark”或类似程序来嗅探通信,以查看发送/接收的实际内容。这将更好地为您指出问题

标签: http networking haskell


【解决方案1】:

您需要指定一个Content-Length HTTP header,其值必须是原始发布数据的长度:

updateTest = Request { rqURI     = updateURI
                     , rqMethod  = POST
                     , rqHeaders = [ mkHeader HdrContentType "application/x-www-form-urlencoded"
                                   , mkHeader HdrContentLength "8"
                                   ]
                     , rqBody    = "raw data"
                     }

【讨论】:

    【解决方案2】:

    还有http-conduit:

    {-# LANGUAGE OverloadedStrings #-}
    
    import Network.HTTP.Conduit
    import qualified Data.ByteString.Lazy as L
    
    main = do
      initReq <- parseUrl "http://localhost/test.php"
    
      let req = (flip urlEncodedBody) initReq $
                 [ ("", "Test string")
    --             ,
                 ]
    
      response <- withManager $ httpLbs req
    
      L.putStr $ responseBody response
    

    "Test string",在上面的例子中,在发布之前是 urlEncoded。

    您也可以手动设置方法、内容类型和请求正文。 api 与 http-enumerator 中的相同,一个很好的例子是: https://stackoverflow.com/a/5614946

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多