Reputation: 135
So this is just a simple example that just pulls in the google homepage information. But what I would like to do is get data from a rest API using HttpClient in C# .NET Framework but the issue is I couldn't figure out how to add in 2 authentication headers, the two parameters should be for like a API-Key and an API-Secret-Key. Here is the code I have right now.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Reporting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string StartDate = dtpStartDate.Text;
string EndDate = dtpEndDate.Text;
Main();
async Task Main()
{
try
{
var client = new HttpClient();
// Call asynchronous network methods in a try/catch block to handle exceptions.
HttpResponseMessage response = await client.GetAsync("https://www.google.com");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
label1.Text = responseBody;
}
catch (Exception ex)
{
label2.Text = ex.ToString();
//throw ex;
}
}
}
}
}
Upvotes: 1
Views: 347
Reputation: 307
Can you try the following, please
client.DefaultRequestHeaders.Add("API-Key", "");
client.DefaultRequestHeaders.Add("API-Secret-Key", "");
Note that this does add the headers for the lifetime of the HttpClient
Upvotes: 2