我正在使用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);
}
答案 0 :(得分:0)
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "user", "pass"))));
实际上这行代码确实很好用