为 WebClient 请求设置 User-Agent 标头 [英] Setting the User-Agent header for a WebClient request

查看:44
本文介绍了为 WebClient 请求设置 User-Agent 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为 Windows Phone 7 的 WebClient 请求设置 User-Agent 标头的正确方法是什么?我找到了 2 个选项,但不确定哪一个是正确的.考虑一个 WebClient 对象:

What is the proper way of setting the User-Agent header for a WebClient request for Windows Phone 7? I found 2 options, but not sure which one is the correct one. Considering a WebClient object:

WebClient client = new WebClient();

我看到了 2 个选项:

I saw 2 options:

  1. 使用以下方法设置用户代理:

  1. set the User-Agent using:

client.Headers["User-Agent"] = "myUserAgentString";

  • 使用 WebHeaderCollection 设置用户代理:

  • set the User-Agent using the WebHeaderCollection:

    WebHeaderCollection headers = new WebHeaderCollection();
    headers[HttpRequestHeader.UserAgent] = "userAgentString";
    client.Headers = headers;
    

  • 你能告诉我上面两种方法中哪一种是正确的吗?

    Can you please advise which of the 2 methods above is the proper one?

    推荐答案

    您可以查看WebClient 文档,用于将用户代理添加到您的 WebClient此处获取 Windows Phone 示例.

    You can check the WebClient documentation for a C# sample that adds a User-Agent to your WebClient and here for a sample for Windows Phone.

    这是 C# 的示例:

    WebClient client = new WebClient ();
    
    // Add a user agent header in case the 
    // requested URI contains a query.
    
    client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " + 
                                      "Windows NT 5.2; .NET CLR 1.0.3705;)");
    

    这是 Windows Phone (Silverlight) 的示例:

    This is a sample for Windows Phone (Silverlight):

    request.Headers["UserAgent"] = "appname";
    // OR
    request.UserAgent = "appname";
    

    这篇关于为 WebClient 请求设置 User-Agent 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆