naett: Set timeout, POST body, etc. Just missing user agent

This commit is contained in:
Henrik Rydgård 2023-07-21 10:06:04 +02:00
parent ab6e902fea
commit 96a75f9fc4

View File

@ -21,9 +21,28 @@ HTTPSDownload::~HTTPSDownload() {
void HTTPSDownload::Start() { void HTTPSDownload::Start() {
_dbg_assert_(!req_); _dbg_assert_(!req_);
_dbg_assert_(!res_);
const char *methodStr = method_ == RequestMethod::GET ? "GET" : "POST"; std::vector<naettOption *> options;
req_ = naettRequest_va(url_.c_str(), !postMime_.empty() ? 3 : 2, naettMethod(methodStr), naettHeader("accept", "application/json, text/*; q=0.9, */*; q=0.8"), naettHeader("Content-Type", postMime_.c_str())); options.push_back(naettMethod(method_ == RequestMethod::GET ? "GET" : "POST"));
options.push_back(naettHeader("Accept", acceptMime_));
if (!postMime_.empty()) {
options.push_back(naettHeader("Content-Type", postMime_.c_str()));
}
if (method_ == RequestMethod::POST) {
if (!postData_.empty()) {
// Note: Naett does not take ownership over the body.
options.push_back(naettBody(postData_.data(), (int)postData_.size()));
}
} else {
_dbg_assert_(postData_.empty());
}
// 30 s timeout - not sure what's reasonable?
options.push_back(naettTimeout(30 * 1000)); // milliseconds
const naettOption **opts = (const naettOption **)options.data();
req_ = naettRequestWithOptions(url_.c_str(), (int)options.size(), opts);
res_ = naettMake(req_); res_ = naettMake(req_);
} }
@ -46,7 +65,11 @@ bool HTTPSDownload::Done() {
if (completed_) if (completed_)
return true; return true;
if (naettComplete(res_)) { if (!naettComplete(res_)) {
// Not done yet, return and try again later.
return false;
}
resultCode_ = naettGetStatus(res_); resultCode_ = naettGetStatus(res_);
if (resultCode_ < 0) { if (resultCode_ < 0) {
// It's a naett error. Translate and handle. // It's a naett error. Translate and handle.
@ -66,13 +89,16 @@ bool HTTPSDownload::Done() {
case naettGenericError: // -4 case naettGenericError: // -4
ERROR_LOG(IO, "Generic error"); ERROR_LOG(IO, "Generic error");
break; break;
default:
ERROR_LOG(IO, "Unhandled naett error %d", resultCode_);
break;
} }
failed_ = true;
} else if (resultCode_ == 200) { } else if (resultCode_ == 200) {
int bodyLength; int bodyLength;
const void *body = naettGetBody(res_, &bodyLength); const void *body = naettGetBody(res_, &bodyLength);
char *dest = buffer_.Append(bodyLength); char *dest = buffer_.Append(bodyLength);
memcpy(dest, body, bodyLength); memcpy(dest, body, bodyLength);
if (!outfile_.empty() && !buffer_.FlushToFile(outfile_)) { if (!outfile_.empty() && !buffer_.FlushToFile(outfile_)) {
ERROR_LOG(IO, "Failed writing download to '%s'", outfile_.c_str()); ERROR_LOG(IO, "Failed writing download to '%s'", outfile_.c_str());
} }
@ -88,9 +114,6 @@ bool HTTPSDownload::Done() {
return true; return true;
} }
return false; } // namespace http
}
} // namespace
#endif // HTTPS_NOT_AVAILABLE #endif // HTTPS_NOT_AVAILABLE