net_util.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_WINHTTP_NET_UTIL_H_
  5. #define COMPONENTS_WINHTTP_NET_UTIL_H_
  6. #include <windows.h>
  7. #include <winhttp.h>
  8. #include <stdint.h>
  9. #include <string>
  10. #include "base/check_op.h"
  11. namespace winhttp {
  12. // Returns the last error as an HRESULT or E_FAIL if last error is NO_ERROR.
  13. // This is not a drop in replacement for the HRESULT_FROM_WIN32 macro.
  14. // The macro maps a NO_ERROR to S_OK, whereas the HRESULTFromLastError maps a
  15. // NO_ERROR to E_FAIL.
  16. HRESULT HRESULTFromLastError();
  17. // Returns HTTP response headers from the given request as strings.
  18. HRESULT QueryHeadersString(HINTERNET request_handle,
  19. uint32_t info_level,
  20. const wchar_t* name,
  21. std::wstring* value);
  22. // Returns HTTP response headers from the given request as integers.
  23. HRESULT QueryHeadersInt(HINTERNET request_handle,
  24. uint32_t info_level,
  25. const wchar_t* name,
  26. int* value);
  27. // Queries WinHTTP options for the given |handle|. Returns S_OK if the call
  28. // is successful.
  29. template <typename T>
  30. HRESULT QueryOption(HINTERNET handle, uint32_t option, T* value) {
  31. auto num_bytes = sizeof(*value);
  32. if (!::WinHttpQueryOption(handle, option, value, &num_bytes)) {
  33. DCHECK_EQ(sizeof(*value), num_bytes);
  34. return HRESULTFromLastError();
  35. }
  36. return S_OK;
  37. }
  38. // Sets WinHTTP options for the given |handle|. Returns S_OK if the call
  39. // is successful.
  40. template <typename T>
  41. HRESULT SetOption(HINTERNET handle, uint32_t option, T value) {
  42. if (!::WinHttpSetOption(handle, option, &value, sizeof(value)))
  43. return HRESULTFromLastError();
  44. return S_OK;
  45. }
  46. } // namespace winhttp
  47. #endif // COMPONENTS_WINHTTP_NET_UTIL_H_