Basic authentication with Qt (QNetworkAccessManager)

╄→гoц情女王★ 提交于 2019-11-27 21:19:27

问题


I was trying to perform basic authentication for Twitter from my Qt app. I use QNetworkAccessManager. But I couldn't find any help on this.

But I found a program called qsoapmanager which passes credentials in base64 through the header. Maybe I can do this with QNAM by setting header in QNetowrkRequest. But I failed to find a way.

In qsoapman source, header is set like this:

QHttpRequestHeader header;

header.setValue( "Authorization", QString( "Basic " ).append( auth.data() ) );

Can I do just that with QNAM/QNReq or is there a better way?


回答1:


The recommended way is to connect to the authenticationRequired signal and set the credentials from there.




回答2:


But if you want to do it by just setting the header value, here's how you can do that:

// HTTP Basic authentication header value: base64(username:password)
QString concatenated = username + ":" + password;
QByteArray data = concatenated.toLocal8Bit().toBase64();
QString headerData = "Basic " + data;
request.setRawHeader("Authorization", headerData.toLocal8Bit());



回答3:


Just using qNetworkAccessManager normally but add

setRawHeader("Authorization", headerData.toLocal8Bit());

to your request.

Example:

//authentication

QString concatenated = "admin:admin"; //username:password

QByteArray data = concatenated.toLocal8Bit().toBase64();

QString headerData = "Basic " + data;

QNetworkRequest request=QNetworkRequest(QUrl("http://192.168.1.10/getinfo"));

request.setRawHeader("Authorization", headerData.toLocal8Bit());

networkAccessManager->get(request);

`



来源:https://stackoverflow.com/questions/1512849/basic-authentication-with-qt-qnetworkaccessmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!