0

我是这个论坛的新手。

我正在尝试使用 Httclient 为我的 Windows 应用程序进行基本身份验证。

var handler2 = new HttpClientHandler
{
Credentials = new NetworkCredential(username, password)
};
var httpClient2 = new HttpClient(handler2);
httpClient2.DefaultRequestHeaders.Add("user-Agent", "authentication.cs");
var response2 = httpClient.GetAsync(uri);

我有两个问题:

我需要添加标题内容类型和用户代理。不知道如何添加它们。有人可以帮帮我。

作为回应,我得到了空值。知道为什么吗?

问候,

TM值

4

1 回答 1

0

您可以通过执行添加用户代理标头

    client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("authentication.cs"));

您不能将 Content-Type 添加到默认请求标头,因为您只能在使用 PUT 或 POST 发送一些内容时设置 Content-Type。我猜你想像这样设置 Accept 标头:

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));

更新:没有我自己的帐户,这是我能做到的。

公共密封部分类 MainPage : Page { private readonly HttpClient _httpClient = new HttpClient();

    public MainPage()
    {
        this.InitializeComponent();
        InitHttpClient();

    }

    private void InitHttpClient() {
        var username = "youremail@somewhere.com";
        var password = "yourharvestpassword";
        String authparam = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authparam);
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
        _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyHarvestClient", "1.0"));
    }

    /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.  The Parameter
    /// property is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e) {

        _httpClient.GetAsync("https://yoursubdomain.harvestapp.com/projects")
            .ContinueWith(t => HandleResponse(t.Result));
    }

    private void HandleResponse(HttpResponseMessage response) {
        response.EnsureSuccessStatusCode();

        var contentString = response.Content.ReadAsStringAsync().Result;  
        var contentXML = XDocument.Parse(contentString);

    }
}
于 2013-01-10T02:17:18.217 回答