Windows 8 Httpclient基本身份验证

时间:2013-01-08 10:09:41

标签: dotnet-httpclient

我是这个论坛的新手。

我正在尝试使用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

1 个答案:

答案 0 :(得分: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);

    }
}