来自PHP示例的UWP HttpClient授权

时间:2016-03-24 06:55:57

标签: c# php http web uwp

我正在使用HttpClient从网址获取http内容。有人在php为我提供了一些示例,我应该使用用户名和密码进行服务:

$user = "testUser";
$passwd = "testPassword";
$url = "testurl";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$passwd");
$output = curl_exec($ch);
curl_close($ch);
echo $output;

如何将其转换为c#代码并提供用户名和密码?

现在我的代码看起来像这样,但没有帮助:

string url = "my url";
var result = string.Empty;
var client = new HttpClient();
var msg = await client.GetAsync(url);
if (msg.IsSuccessStatusCode)
{
    var data = await msg.Content.ReadAsByteArrayAsync();
    result = encoding.GetString(data);
}

1 个答案:

答案 0 :(得分:0)

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
    Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "user", "pass"))));

实际上这行代码确实很好用