Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to easily get https post response data?

Tags:

I'm developing a toy program which uses the Google URL shortener API. To shorten a URL, you need to send this request:

POST https://www.googleapis.com/urlshortener/v1/url Content-Type: application/json  {"longUrl": "http://www.google.com/"} 

and you will get this as response:

{  "kind": "urlshortener#url",  "id": "http://goo.gl/fbsS",  "longUrl": "http://www.google.com/" } 

At first I use Network.HTTP, but found it doesn't support HTTPS, and Google's API only supports HTTPS. So I turn to Network.Curl. I find that there's a convenient function for HTTP GET

curlGetString :: URLString -> [CurlOption] -> IO (CurlCode, String) 

but there's no such a function for HTTP POST. Even worse, I can't find a way to get the response data of HTTP POST. All I know is that I can issue a HTTP POST request using

curlPost :: URLString -> [String] -> IO () 

Could anyone show me a way out? Thanks.

like image 338
kevin Chen Avatar asked Apr 10 '11 13:04

kevin Chen


People also ask

Can I use POST method to retrieve data?

Can I use POST method to get data from the server and GET method to post data to the server? A POST request can have a response, but a GET request can't have a body (well technically it can, but there's surprisingly few systems that support it). Therefore this question makes no sense.

How do you POST data in a URL?

Use Postman by Google, which allows you to specify the content-type (a header field) as application/json and then provide name-value pairs as parameters. Just use your URL in the place of theirs. What if you send all the arguments in the URL, like with a GET request?

Does HTTP GET have a body?

GET requests don't have a request body, so all parameters must appear in the URL or in a header. While the HTTP standard doesn't define a limit for how long URLs or headers can be, mostHTTP clients and servers have a practical limit somewhere between 2 kB and 8 kB.

Can you send body with GET request?

So, yes, you can send a body with GET, and no, it is never useful to do so. This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress). Yes, you can send a request body with GET but it should not have any meaning.


1 Answers

Just to provide an alternative solution via use of http-enumerator:

{-# LANGUAGE OverloadedStrings #-}  import Network.HTTP.Enumerator import Network.HTTP.Types import qualified Data.ByteString.Lazy as L  main = do   req0 <- parseUrl "https://www.googleapis.com/urlshortener/v1/url"    let req = req0 { method = methodPost                  , requestHeaders = [("Content-Type", "application/json")]                  , requestBody = RequestBodyLBS "{\"longUrl\": \"http://www.google.com/\"}"                  }    res <- withManager $ httpLbs req    L.putStrLn $ responseBody res 
like image 138
hvr Avatar answered Sep 19 '22 01:09

hvr