urllib error when using Python 3

Viewed 1314

Whenever I run the below code in Python 3 I get a syntax error invalid syntax. The reason for this I assume is because print in python 3 has different syntax.

import sys
from urllib.request import urlopen
from urllib.request import Request
import json

request = Request(
    "https://gcm-http.googleapis.com/gcm/send",
    dataAsJSON,
    { "Authorization" : "key="+MY_API_KEY,
      "Content-type" : "application/json"
    }
)

print urlopen(request).read()

however, when I change my last line to

result = urlopen(request).read()

I get the following error:

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

1 Answers

Convert your data to byte string before creating request object.

dataAsJSON = dataAsJSON.encode()
Related