1

发送添加了用户代理的 QHTTP 请求

C:\Python33\Lib\site-packages\PyQt4\examples\network\http 中有一个示例

但我想将 User-Agent 标头添加到 http 请求中,所以我评论了

##        self.httpGetId = self.http.get(path, self.outFile)

并编写以下代码

header = QtNetwork.QHttpRequestHeader("GET", path)#1
header.setValue("Host", url.host())
header.setValue('User-Agent' ,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17')

self.http.setHost(url.host())

那么问题来了,我不知道如何发送这个请求并将标头添加到服务器?

PS我参考了文档,也许找到了

int QHttp::request ( const QHttpRequestHeader & header, QIODevice * data = 0, QIODevice * to = 0 )

会来帮我解决这个问题,但我想知道在这种情况下应该是什么“数据”?

4

1 回答 1

1

使用 aQNetworkAcessManager发送您的请求,如下所示:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtNetwork

if __name__ == '__main__':
    import sys

    print "Starting request...",

    app = QtCore.QCoreApplication(sys.argv)
    url = QtCore.QUrl("http://www.example.com/")

    request = QtNetwork.QNetworkRequest()
    request.setUrl(url)
    request.setRawHeader("User-Agent", "MyAppName/1.0 (Nokia; Qt)")

    manager = QtNetwork.QNetworkAccessManager()
    manager.finished.connect(app.quit)
    manager.get(request)

    print "done."

    sys.exit(app.exec_())
于 2013-04-12T22:16:42.473 回答