7

I'm doing some work with PyQt4 and QtWebKit, and in the web page request need to send a custom "Host" header along with the standard HTTP request. I'm not seeing any options for adding custom headers to the request, but this is all new to me so I hope I'm missing something. I'm looking here:

http://doc.qt.digia.com/4.6/qwebsettings.html

Any advice would be greatly appreciated.

mavroprovato
  • 8,023
  • 5
  • 37
  • 52
lennysan
  • 1,330
  • 2
  • 13
  • 16

2 Answers2

11

You can set headers on the QNetworkRequest that is sent:

QNetworkRequest request;
request.setUrl(QUrl("http://qt.nokia.com"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");

To use that custom request when loading a page, use the overloaded load function:

myWebView->load(request);
mavroprovato
  • 8,023
  • 5
  • 37
  • 52
Kaleb Pederson
  • 45,767
  • 19
  • 102
  • 147
  • Does this override all of the default headers, or does this just add and replace existing headers? – lennysan Sep 07 '10 at 22:54
  • Any idea why it would hang when I use a "Host: mysite.com" but works fine when i use "Host: www.mysite.com"? I would expect the webserver to respond in either case, but in the first case the call just sits there indefinitely. – lennysan Sep 08 '10 at 00:08
  • That behavior depends on the web server being used. When a server supports multiple (virtual) hosts, it must use the `host` header to determine to which virtual host the request should be sent. – Kaleb Pederson Sep 08 '10 at 00:16
  • I am using web app that could allow specific User-Agent to allow and my [code](https://gist.github.com/tbhaxor/f4ffef16eb7bea33f910e55bd516a433) and user agent is not showing any effect .. – tbhaxor Mar 28 '19 at 09:38
3

If you want to apply this to all requests QtWebKit makes, you can subclass QNetworkAccessManager and reimplement its createRequest() function to modify headers accordingly.

kralyk
  • 4,249
  • 1
  • 32
  • 34
  • Could you please tell how it is possible to be implemented if createRequest() accepts QNetworkRequest by const reference? As I can imagine setHeader() or setRawHeader() of the corresponding QNetworkRequest should be called. – NuPagadi Dec 02 '16 at 18:26