Skip to content

Commit 859292a

Browse files
MathyVras0219-msft
authored andcommitted
Make it possible to set the user agent for websockets (microsoft#606)
* Make it possible to set the user agent for websockets * Use headers() to communicate the user agent for websockets. * Fix set_user_agent on Linux; use to_string_t.
1 parent 377677d commit 859292a

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Release/include/cpprest/ws_client.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ class websocket_client_config
150150
return m_sni_hostname;
151151
}
152152

153+
/// <summary>
154+
/// Sets the User Agent to be used for the connection
155+
/// </summary>
156+
/// <param name="name">The User Agent to use, as a string.</param>
157+
_ASYNCRTIMP void set_user_agent(const utf8string &user_agent);
158+
153159
/// <summary>
154160
/// Gets the headers of the HTTP request message used in the WebSocket protocol handshake.
155161
/// </summary>

Release/src/websockets/client/ws_client_wspp.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,15 @@ class wspp_callback_client : public websocket_client_callback_impl, public std::
316316
shutdown_wspp_impl<WebsocketConfigType>(con_hdl, false);
317317
});
318318

319+
// Set User Agent specified by the user. This needs to happen before any connection is created
320+
const auto& headers = m_config.headers();
321+
322+
auto user_agent_it = headers.find(web::http::header_names::user_agent);
323+
if (user_agent_it != headers.end())
324+
{
325+
client.set_user_agent(utility::conversions::to_utf8string(user_agent_it->second));
326+
}
327+
319328
// Get the connection handle to save for later, have to create temporary
320329
// because type erasure occurs with connection_hdl.
321330
websocketpp::lib::error_code ec;
@@ -327,7 +336,6 @@ class wspp_callback_client : public websocket_client_callback_impl, public std::
327336
}
328337

329338
// Add any request headers specified by the user.
330-
const auto & headers = m_config.headers();
331339
for (const auto & header : headers)
332340
{
333341
if (!utility::details::str_icmp(header.first, g_subProtocolHeader))

Release/src/websockets/client/ws_msg.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ namespace client
2828
{
2929

3030
static ::utility::string_t g_subProtocolHeader = _XPLATSTR("Sec-WebSocket-Protocol");
31+
32+
void websocket_client_config::set_user_agent(const utf8string &user_agent)
33+
{
34+
headers().add(web::http::header_names::user_agent, utility::conversions::to_string_t(user_agent));
35+
}
36+
3137
void websocket_client_config::add_subprotocol(const ::utility::string_t &name)
3238
{
3339
m_headers.add(g_subProtocolHeader, name);

0 commit comments

Comments
 (0)