使用 Python 3 时出现 urllib 错误

urllib error when using Python 3

每当我 运行 Python 3 中的以下代码时,我都会收到语法错误 invalid syntax。我认为这样做的原因是因为 print in python 3 具有不同的语法。

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()

然而,当我将最后一行更改为

result = urlopen(request).read()

我收到以下错误:

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

在创建 request 对象之前将您的数据转换为字节字符串。

dataAsJSON = dataAsJSON.encode()