Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to modify the User-Agent for a WinRT HttpWebRequest?

I am trying to convert an existing app to a Metro UI app in VS 11 Developer Preview. This means running against the WinRT runtime (correct me if I'm wrong). This runs on the Windows 8 Developer Preview.

I need to call a REST API, which requires a specific user-agent to be set. This doesn't seem to be possible in WInRT. I have the following original code:

_request = WebRequest.CreateHttp(url);
_request.UserAgent = UserAgent;

But the UserAgent property is not defined for HttpWebRequest. I also tried:

_request.Headers["User-Agent"] = UserAgent;

This results in a runtime exception: System.ArgumentException: This header must be modified using the appropriate property or method.

How can I modify the User-Agent header ?

like image 600
driis Avatar asked Sep 17 '11 11:09

driis


2 Answers

After some tinkering around, I have now worked out how to do this in WinRT. The HttpWebRequest API has changed in this version to be a lot poorer than in the full .NET Framework. However, I can send a request with the new HttpClient API, which will allow me to send the user-agent header:

var req = new HttpClient(handler)
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("User-Agent", "myCustomUserAgent");
var response = await req.SendAsync(message);
like image 159
driis Avatar answered Nov 11 '22 18:11

driis


Just to note that in Windows 10 it is possible to do it exactly like in the example in your question.

like image 37
Ivan Ičin Avatar answered Nov 11 '22 19:11

Ivan Ičin