我正在尝试使用Haskell仆人库为newsapi.org提供的News api进行客户端绑定。我创建了以下端点:
type NewsAPI = "top-headlines" :> QueryParam "country" String :> QueryParam "apiKey" String :> Get '[JSON] TopHeadlines
并尝试如下调用它:
topheadlines :: Maybe String -> Maybe String -> ClientM TopHeadlines
api :: Proxy NewsAPI
api = Proxy
topheadlines = client api
query = topheadlines (Just "us") (Just "<api key>")
run3 :: IO ()
run3 = do
manager' <- newManager defaultManagerSettings
users <- runClientM query (mkClientEnv manager' (BaseUrl Https "newsapi.org/v2" 443 ""))
print users
我不断收到一个连接错误,我不完全理解如何解释该错误:
Left (ConnectionError "HttpExceptionRequest Request {\n host = \"newsapi.org/v2\"\n port = 443\n secure = True\n requestHeaders = [(\"Accept\",\"application/json;charset=utf-8,application/json\")]\n path = \"/top-headlines\"\n queryString = \"?country=us&api_key=90a38fab85c440fa88521e0789248f83\"\n method = \"GET\"\n proxy = Nothing\n rawBody = False\n redirectCount = 10\n responseTimeout = ResponseTimeoutDefault\n requestVersion = HTTP/1.1\n}\n TlsNotSupported")
不确定为什么没有连接。我拥有的另一组客户端绑定工作正常。
答案 0 :(得分:0)
这是两件事的结合:
api_key
应该是apiKey
依靠parseBaseUrl
burl <- parseBaseUrl "http://newsapi.org/v2"
这在我设置的示例项目中对我有用。
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Control.Monad.Free
import Servant.Client.Free
import qualified Network.HTTP.Client as HTTP
import qualified Servant.Client.Internal.HttpClient as I
import Network.Wai.Handler.Warp (run)
import Servant
import System.Environment (getArgs)
type NewsAPI = "top-headlines" :> QueryParam "country" String :> QueryParam "apiKey" String :> Get '[JSON] String
topheadlines :: Maybe String -> Maybe String -> Free ClientF String
topheadlines = client api
api :: Proxy NewsAPI
api = Proxy
main :: IO ()
main = do
test
test :: IO ()
test = case topheadlines (Just "us") (Just "API_KEY") of
Pure n ->
putStrLn $ "ERROR: got pure result: " ++ show n
Free (Throw err) ->
putStrLn $ "ERROR: got error right away: " ++ show err
Free (StreamingRequest _req _k) ->
putStrLn $ "ERROR: need to do streaming request"
Free (RunRequest req k) -> do
burl <- parseBaseUrl "http://newsapi.org/v2"
mgr <- HTTP.newManager HTTP.defaultManagerSettings
let req' = I.requestToClientRequest burl req
putStrLn $ "Making request: " ++ show req'
res' <- HTTP.httpLbs req' mgr
putStrLn $ "Got response: " ++ show res'