QT之HTTP
作者:互联网
概述
还没有写完,以后再补
相关类:
QNetworkAccessManager 【发送网络请求并接收响应】
QNetworkReply 【服务响应】
QNetworkRequest 【服务请求】
QUrl
要使用这些类,需要在pro文件中加入network模块。QT += network
发送一个GET请求
QNetworkRequest request;
request.setHeader(QNetworkRequest::UserAgentHeader,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36");
request.setUrl(QUrl(url));
QNetworkAccessManager* manager = new QNetworkAccessManager;
QNetworkReply* reply = manager->get(request);
QEventLoop eventLoop;
connect(manager,&QNetworkAccessManager::finished,&eventLoop,&QEventLoop::quit);
eventLoop.exec();
QString responseText = reply->readAll();
int responseStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
设置代理
QNetworkProxy类提供了一个网络层代理
QNetworkProxy目前支持的类有QAbstractSocket、QTcpSocket、QUdpSocket、QTcpServer和QNetworkAccessManager
使用方法:
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::Socks5Proxy); // http代理:QNetworkProxy::HttpProxy
proxy.setHostName("127.0.0.1");
proxy.setPort(1080);
proxy.setUser("username");
proxy.setPassword("password");
m_network->setProxy(proxy);
// 禁用代理
m_network->setProxy(QNetworkProxy::NoProxy);
Cookie相关操作
获取返回的cookie
QNetworkAccessManager* m_network = new QNetworkAccessManager;
...
QNetworkCookieJar* jar = m_network->cookieJar();
QList<QNetworkCookie> list = jar->cookiesForUrl(url);
...
设置cookie
QList<QNetworkCookie> list;
list.append(QNetworkCookie("isAdmin","1"));
QVariant var;
var.setValue(list);
request.setHeader(QNetworkRequest::CookieHeader,var);
设置HTTP头
HTTP头设置有两个方法,分别是:setHeader
,setRawHeader
使用setRawHeader就行了,如:
request.setRawHeader("User-Agent","izero v1.0");
标签:QNetworkRequest,HTTP,network,QNetworkProxy,request,proxy,QT,QNetworkAccessManage 来源: https://www.cnblogs.com/bk76120/p/13824065.html