Reputation: 23
I'm trying to learn how to work with a REST API. Unfortunately the one i'm using requires authentication and I can't get my code right. Anyone willing to help me get my code straight?
using System;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace HttpClientAuth
{
class Program
{
static async Task Main(string[] args)
{
var userName = "admin";
var passwd = "adminpw";
var url = "http://10.10.102.109/api/v1/routing/windows/Window1";
using var client = new HttpClient();
var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authToken));
var result = await client.GetAsync(url);
var requestContent = new HttpRequestMessage(HttpMethod.Post, url);
//Request Body in Key Value Pair
requestContent.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["CanYCentre"] = "540",
["CanXCentre"] = "960",
});
var content = await result.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}
}
Upvotes: 1
Views: 1505
Reputation: 23
For those looking for an alternative version of a C# Http JSON PUT with Authentication:
using System;
using System.Text;
using System.Net;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
//URL
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
//Basic Authentication
string authInfo = "admin" + ":" + "adminpw";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;
//Application Type
httpWebRequest.ContentType = "application/json";
//Method
httpWebRequest.Method = "PUT";
// JSON Body
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ID\":\"1\"," +
"\"Phone\":\"1234567890\"}";
streamWriter.Write(json);
Console.WriteLine("PUT Body: " + json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
//Status Code
Console.WriteLine("URL: " + httpWebRequest.RequestUri);
Console.WriteLine("Status Discription " + httpResponse.StatusDescription);
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("Status code " +(int)httpResponse.StatusCode + " " + httpResponse.StatusCode);
}
else
{
Console.WriteLine("Status code " + (int)httpResponse.StatusCode + " " + httpResponse.StatusCode);
}
// Close the response.
httpResponse.Close();
}
}
}
Upvotes: 1
Reputation: 22419
Seems you are confused how you could make a POST
request. You could try below snippet.
ApiRequestModel _requestModel = new ApiRequestModel();
_requestModel.RequestParam1 = "YourValue";
_requestModel.RequestParam2= "YourValue";
var jsonContent = JsonConvert.SerializeObject(_requestModel);
var authKey = "c4b3d4a2-ba24-46f5-9ad7-ccb4e7980da6";
var requestURI = "http://10.10.102.109/api/v1/routing/windows/Window1";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(requestURI);
request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "Basic" + authKey);
var response = await client.SendAsync(request);
//Check status code and retrive response
if (response.IsSuccessStatusCode)
{
dynamic objResponse = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
}
else
{
dynamic result_string = await response.Content.ReadAsStringAsync();
}
}
Update: As per your given screenshot on comment you could also try this way.
private async Task<string> HttpRequest()
{
//Your Request End Point
string requestUrl = $"http://10.10.102.109/api/v1/routing/windows/Window1";
var requestContent = new HttpRequestMessage(HttpMethod.Post, requestUrl);
//Request Body in Key Value Pair
requestContent.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["CanYCentre"] = "540",
["CanXCentre"] = "960",
});
requestContent.Headers.Add("Authorization", "Basic" + "YourAuthKey");
HttpClient client = new HttpClient();
//Sending request to endpoint
var tokenResponse = await client.SendAsync(requestContent);
//Receiving Response
dynamic json = await tokenResponse.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject<dynamic>(json);
return response;
}
Update 2:
If you still don't understand or don't know how you would implement it Just copy and paste below code snippet.
private static async Task<string> HttpRequest()
{
object[] body = new object[]
{
new { CanYCentre = "540" },
new { CanYCentre = "960" }
};
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("http://10.10.102.109/api/v1/routing/windows/Window1");
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "Basic" + "YourAuthKey");
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
dynamic result = JsonConvert.DeserializeObject<dynamic>(responseBody);
return result;
}
}
Hope this would help you. If you encounter any problem feel free to share.
Upvotes: 2