Rahul Rathod
Rahul Rathod

Reputation: 27

How to get data from API by using post method in Roku?

I want to get data from API in Roku by passing parameter in body using post method if any one have any idea please late me know.

Upvotes: 1

Views: 779

Answers (1)

TwitchBronBron
TwitchBronBron

Reputation: 3186

You can use the roURLTransfer's AsyncPostFromString() method to do a post request. Just make sure to set the Content-Type header first so the server knows how to interpret the post body.

Here's a function that will send a POST request and return the body. This must be run from a Task.

function httpPost(url as string, requestBody as dynamic)
  'create the request
  request = createObject("roUrlTransfer")

  'set the HTTP method. can be "GET", "POST", "PUT", etc...
  request.setRequest("POST")
  request.SetUrl(url)

  'assign the headers to the request,
  request.setHeaders({
    'set the content-type header
    "Content-Type": "application/json"
  })

  'create a message port to monitor for the response
  port = createObject("roMessagePort")
  'assign the message port to the request
  request.SetMessagePort(port)

  'send the request in the background
  responseCode = request.AsyncPostFromString(formatJson(requestBody))

  'wait infinitely for the response
  response = wait(0, port)

  responseCode = response.GetResponseCode()
  'this is the post body
  responseBody = response.GetString()
  return responseBody
end function

Just FYI, this implementation runs a blocking wait, so it requires a new Task for every request (which can be hard on lower-end Roku devices if used excessively). Ideally, you'd create a long-lived task that takes multiple requests, and attach the same message port to all of them, and monitor for responses. But that's out of scope for the current request. Check out the uri-fetcher example from Roku's samples repository for an idea on how to handle that.

Upvotes: 2

Related Questions