Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

urllib error when using Python 3

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.

like image 898
tony9099 Avatar asked Aug 31 '26 08:08

tony9099


1 Answers

Convert your data to byte string before creating request object.

dataAsJSON = dataAsJSON.encode()
like image 90
hspandher Avatar answered Sep 02 '26 12:09

hspandher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!