概述
QT的HTTP操作都是异步的,内部通过线程实现。
相关类:
QNetworkAccessManager 【发送网络请求并接收响应】
QNetworkReply 【服务响应】
QNetworkRequest 【服务请求】
QUrl
要使用这些类,需要在pro文件中加入network模块。QT += network
发送一个GET请求
void TestClass::on_pushButton_2_clicked()
{
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;
manager->get(request); // 发送请求
connect(manager,&QNetworkAccessManager::finished,this,&TestClass::reply_response);
}
void TestClass::reply_response(QNetworkReply* reply)
{
QString responseText = reply->readAll(); // 获取网页数据
int responseStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // 获取HTTP状态码
}
设置代理
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");