2017-10-29 130 views
0

我正在用C#编写代码来构建控制台来实现获取请求。 我们使用POSTMAN来完成任务,但我们决定建立自己的。C#中的授权标头和内容类型#

我需要在请求的标题中传递用户名和密码。 由于我是编程新手,你能指导我吗?

我已经写了下面的代码:

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

是什么网址...它在邮递员上工作..你在哪里设置头和应用程序类型在HttpClient? –

+1

如果你花时间寻找答案而不是要求答案,那将会很棒。 –

回答

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)); 
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));