0

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.

Thank you!

1 Answers1

1

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.

TwitchBronBron
  • 2,783
  • 3
  • 21
  • 45
  • I have the same request and we're asking how to "get data" from a POST. As per your sample, using PostFromString only returns the integer response code and per the docs, the body is discarded. It's a pretty common practice to receive a payload from a POST, is there no way to do this using roUrlTransfer? – Brett Mar 03 '23 at 18:46
  • 1
    Oh, I totally missed that part of the question. I just updated my answer to show how to do a POST request and get the body. – TwitchBronBron Mar 06 '23 at 14:52