HTTP 클라이언트
간단한 HTTP 클라이언트를 보여줍니다.
이 예제는 간단한 HTTP 클라이언트가 원격 호스트에서 파일을 가져오는 방법을 보여줍니다.

이 예제의 주요 작업은 HttpWindow 클래스에서 수행됩니다. 따라서 이 클래스에 중점을 두고 살펴보겠습니다.
QNetworkRequest networkRequest(url);
networkRequest.setTcpKeepAliveIdleTimeBeforeProbes(20s);
networkRequest.setTcpKeepAliveIntervalBetweenProbes(2s);
networkRequest.setTcpKeepAliveProbeCount(5);Qt 6.11부터는 ` QNetworkRequest`에 대한 TCP 키프얼라이브 매개변수를 명시적으로 지정할 수 있습니다. 위의 코드 조각에서는 ` QNetworkAccessManager `가 사용하는 기본값을 재정의하여 보다 적극적인 전략을 따르고 있습니다. 이는 예를 들어, 리눅스에서 네트워크 변경으로 인해 발생하는 네트워크 멈춤 현상을 조기에 감지하는 데 유용할 수 있습니다. 이 예제에서는 30초 동안 활동이 없으면 연결이 종료됩니다.
reply.reset(qnam.get(networkRequest));QNetworkAccessManager 를 사용하여 url 가 가리키는 리소스의 다운로드를 시작합니다. 이 함수나 QNetworkAccessManager::get() 함수에 익숙하지 않거나, 단순히 더 자세히 알아보고 싶다면 해당 함수의 문서와 QNetworkReply 및 QNetworkRequest 에 대한 문서를 참고하십시오.
connect(reply.get(), &QNetworkReply::finished, this, &HttpWindow::httpFinished);
connect(reply.get(), &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);
#if QT_CONFIG(ssl)
connect(reply.get(), &QNetworkReply::sslErrors, this, &HttpWindow::sslErrors);
#endif위에서, 우리는 응답의 일부 신호를 클래스의 슬롯에 연결했습니다. 이 슬롯들은 들어오는 데이터를 처리하고, 다운로드 완료 및 오류 처리를 담당합니다.
connect(reply.get(), &QIODevice::readyRead, this, &HttpWindow::httpReadyRead);수신 데이터 처리에 관해서는, 잠재적인 입력의 최대 다운로드 크기를 알 수 없고 예제 프로그램을 실행할 수 있는 컴퓨터의 메모리를 모두 소모하고 싶지 않기 때문에, QNetworkReply::finished() 대신 QNetworkReply::readyRead()에서 수신 데이터를 처리합니다.
void HttpWindow::httpReadyRead()
{
// This slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (file)
file->write(reply->readAll());
}그런 다음 데이터가 도착하는 대로 파일에 기록합니다. 다소 불편하긴 하지만, 애플리케이션이 피크 시점에 소비하는 메모리 양은 줄어들 것입니다!
connect(reply.get(), &QNetworkReply::sslErrors, this, &HttpWindow::sslErrors);QNetworkReply::sslErrors() 신호를 사용하면 보안 웹사이트(예: HTTPS)에 연결할 때 TLS 핸드셰이크 과정에서 발생할 수 있는 오류도 처리할 수 있습니다.
void HttpWindow::sslErrors(const QList<QSslError> &errors)
{
QString errorString;
for (const QSslError &error : errors) {
if (!errorString.isEmpty())
errorString += '\n';
errorString += error.errorString();
}
if (QMessageBox::warning(this, tr("TLS Errors"),
tr("One or more TLS errors has occurred:\n%1").arg(errorString),
QMessageBox::Ignore | QMessageBox::Abort)
== QMessageBox::Ignore) {
reply->ignoreSslErrors();
}
}이 예제에서는 사용자에게 대화 상자를 표시하여 오류를 무시할지 여부를 선택할 수 있도록 합니다.
QNetworkReply::NetworkError error = reply->error();
const QString &errorString = reply->errorString();
if (error != QNetworkReply::NoError) {
QFile::remove(fi.absoluteFilePath());
// For "request aborted" we handle the label and button in cancelDownload()
if (!httpRequestAborted) {
statusLabel->setText(tr("Download failed:\n%1.").arg(errorString));
downloadButton->setEnabled(true);
}
return;
}오류가 발생하면 QNetworkReply 는 QNetworkReply::errorOccurred() 신호를 발생시킨 다음, QNetworkReply::finished() 신호를 발생시킵니다. 이 예제에서는 후자에만 연결합니다. 해당 슬롯에서 발생할 수 있는 오류를 처리하기 위해 쓰기 중이던 파일을 삭제하고, 상태 레이블을 통해 오류를 표시합니다.
connect(&qnam, &QNetworkAccessManager::authenticationRequired,
this, &HttpWindow::slotAuthenticationRequired);HTTP 인증을 사용하는 웹사이트에 접속할 때, 미리 사용해야 할 인증 정보를 제공하지 않은 경우 웹사이트에서 인증 정보를 요청할 때 이를 처리할 수 있습니다. ` QNetworkAccessManager`를 사용하여 ` QNetworkAccessManager::authenticationRequired()` 신호에 연결된 슬롯에서 이를 처리합니다. 이 연결은 생성자에서 한 번만 수행합니다.
void HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *authenticator)
{
QDialog authenticationDialog;
Ui::Dialog ui;
ui.setupUi(&authenticationDialog);
authenticationDialog.adjustSize();
ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm(), url.host()));
// Did the URL have information? Fill the UI.
// This is only relevant if the URL-supplied credentials were wrong
ui.userEdit->setText(url.userName());
ui.passwordEdit->setText(url.password());
if (authenticationDialog.exec() == QDialog::Accepted) {
authenticator->setUser(ui.userEdit->text());
authenticator->setPassword(ui.passwordEdit->text());
}
}이 예제에서는 사용자가 사용자 이름과 비밀번호를 입력하거나 취소를 선택할 수 있는 대화 상자를 표시합니다. 취소를 선택하면 요청이 실패합니다.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.