C# - WP8.1 应用程序中的 Web 用户代理

C# - User Agent for Web in WP8.1 Apps

一个一直让我困惑的问题,真的可以提供一些见解。

我需要从 http 服务中检索 Json 个对象。当我在控制台 Window 中对此进行测试时,我一直收到 "Internal Server Error : 500",直到我为 WebClient 对象设置 UserAgent 属性。 示例:

WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36");
content = client.DownloadString(url);

现在,如果我需要对 WP8.1 应用程序执行相同的操作,我将如何检测(如果我首先需要?)UserAgent(并设置它)并能够检索数据?

谢谢大家

Windows Phone 8.1 App将使用HttpClient。默认情况下不会设置用户代理。手机网络浏览器的默认用户代理是:

"Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 520) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537"

您可以在 HttpRequestMessage.Headers.UserAgent 属性 上手动设置用户代理。

参考文献:

HttpClient

https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.web.http.headers.httprequestheadercollection.aspx

用户代理

https://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx#ie11\

使用 http 的 class 库默认不添加任何用户代理。从 msdn 页面查看这些行:

By default, no user-agent header is sent with the HTTP request to the web service by the HttpClient object. Some HTTP servers, including some Microsoft web servers, require that a user-agent header be included with the HTTP request sent from the client. The user-agent header is used by the HTTP server to determine how to format some HTTP pages so they render better on the client for different web browsers and form factors (mobile phones, for example). Some HTTP servers return an error if no user-agent header is present on the client request. We need to add a user-agent header to avoid these errors using classes in the Windows.Web.Http.Headers namespace. We add this header to the HttpClient.DefaultRequestHeaders property.

更多详情,请参考下面的link:

How to connect to an HTTP server using Windows.Web.Http.HttpClient (XAML)

另请查看下面的答案(由 Bret Bentzinger 提供)以获得确切的用户代理字符串。