我在C#中编写代码来构建控制台以实现get请求。 我们使用POSTMAN来完成任务,但我们决定建立自己的。
我需要在请求的标头中传递用户名和pw。 由于我是编程新手,你能指导我吗?
我写了以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApp2
{
class Program
{
private static object response;
static void Main(string[] args)
{
GetRequest("https://www.google.com");
Console.ReadKey();
}
async static void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string mycontent = await content.ReadAsStringAsync();
Console.WriteLine(mycontent);
}
}
}
}
}
}
答案 0 :(得分:0)
您可以尝试以下代码段
HttpClient client = new HttpClient()
var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
答案 1 :(得分:0)
DefaultRequestHeaders不起作用,我使用下面的代码片段进行身份验证
string _ContentType = "application/json";
httpWebRequest.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
var _CredentialBase64 = "xxxxxxxxx=";
httpWebRequest.DefaultRequestHeaders.Add("Authorization", String.Format("Basic {0}", _CredentialBase64));