HTTPクライアント
簡単なHTTPクライアントの例を示します。
この例では、単純なHTTPクライアントがリモートホストからファイルを取得する方法を示します。

この例の主な処理は HttpWindow クラスで行われます。したがって、ここではそのクラスに焦点を当てます。
QNetworkRequest networkRequest(url);
networkRequest.setTcpKeepAliveIdleTimeBeforeProbes(20s);
networkRequest.setTcpKeepAliveIntervalBetweenProbes(2s);
networkRequest.setTcpKeepAliveProbeCount(5);Qt 6.11 以降、QNetworkRequest に対して TCP キープアライブのパラメータを明示的に指定できるようになりました。上記のコードスニペットでは、QNetworkAccessManager が使用するデフォルト設定を上書きし、より積極的な戦略を採用しています。これは、例えば Linux におけるネットワーク環境の変化によって引き起こされるネットワークのハングを早期に検出する場合などに役立ちます。 この具体的な例では、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認証を使用するWebサイトに接続する場合、事前に使用する認証情報を指定していなかったとしても、Webサイトから認証情報の入力を求められた際に、その処理を行うことができます。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.