HTTP 클라이언트

간단한 HTTP 클라이언트를 보여줍니다.

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

이 예제의 주요 작업은 HttpWindow 클래스에서 수행됩니다. 따라서 여기에 집중하겠습니다.

reply.reset(qnam.get(QNetworkRequest(url)));

QNetworkAccessManager 을 사용하여 url 에서 가리키는 리소스 다운로드를 시작합니다. 이 함수나 사용된 함수 QNetworkAccessManager::get()에 익숙하지 않거나 더 자세히 살펴보고 싶다면 해당 문서와 QNetworkReplyQNetworkRequest 의 문서를 살펴보세요.

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());
    }
}

이 예에서는 사용자가 사용자 이름과 비밀번호를 입력하거나 취소할 수 있는 대화 상자를 표시합니다. 취소하면 요청이 실패합니다.

예제 프로젝트 @ code.qt.io

© 2025 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.