QNetworkRequest用于生成的图像

时间:2017-01-18 06:21:12

标签: qt

我正在编写一个脚本,让用户重新下载图像,以便始终拥有最新版本。这适用于some static image I found on google。但是,当我尝试在a generated imageanother上使用它时,它会返回HTML代码:

Error: 0 (Unknown error)
Content-Type: text/html
Content: <html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

到目前为止我的代码:

def onNetworkReply(self, reply):
    try:
        print("Error: %s (%s)"%(reply.error(), reply.errorString()))
        print("Content-Type: %s"%reply.header(QNetworkRequest.ContentTypeHeader))
        print("Content: %s"%reply.readAll())
        #if reply.header(QNetworkRequest.ContentTypeHeader) == "image/jpeg":
        imgraw = reply.readAll()#.data()#.decode('utf-8')
        temp_dir = gettempdir()
        filename = self.generateAvatarFileName(self.schid)
        tmp = path.join(temp_dir, filename)
        fn = QFile(tmp)
        fn.open(QIODevice.WriteOnly)
        fn.write(imgraw)
        fn.close
        #with open(tmp, 'wb') as f: f.write(imgraw)
        ts3lib.logMessage("Uploading %s as new avatar."%tmp, ts3defines.LogLevel.LogLevel_INFO, "PyTSon Script", 0)
        self.uploadAvatar(self.schid, tmp, filename)
    except:
        from traceback import format_exc
        try: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "PyTSon Script", 0)
        except: print(format_exc())
    reply.deleteLater()

1 个答案:

答案 0 :(得分:4)

HTTP响应302 Found是网址重定向状态。如果您使用的是Qt 5.6或更高版本,则可以在QNetworkRequest中启用自动重定向( QNetworkRequest :: FollowRedirectsAttribute )。

QString url("http://your/url/pic.png");
QNetworkRequest req(QUrl(url));
req.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
  

QNetworkRequest :: FollowRedirectsAttribute

     

仅请求,输入:QMetaType :: Bool(默认值:false)表示   网络访问API是否应自动遵循HTTP   是否重定向响应。目前重定向是不安全的   从&#34; https&#34;重定向到&#34; http&#34;协议,是不允许的。 (这个   价值在5.6中引入。)