Reputation: 3
I've written a python function to move a router's IO port via a HTTP post request with Basic Authentivation. This works fine. But now I'd like to implement the sam with C#.
Here is my python function:
def io_on(ip='192.168.2.1', username='adm', password='123456'):
if not isinstance(ip, str):
print('not string')
try:
payload ='_ajax=1&_web_cmd=%21%0Aio%20output%201%20on%0A'
r = requests.post('http://{}/apply.cgi'.format(ip), auth=HTTPBasicAuth(username, password), data=payload, timeout=3)
if r.status_code == 200:
print('{} : IO ON'.format(ip))
elif r.status_code == 401:
print('{} : Auth error'.format(ip))
else:
print(r.status_code)
except Exception as e:
print(e)
I've experimented with NetWorkCredentials with no success.
Upvotes: 0
Views: 1284
Reputation: 99
Here's my way to make POST with basic authentication.
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{login}:{password}")));
using (var client = new HttpClient() { DefaultRequestHeaders = { Authorization = authValue } })
{
HttpResponseMessage response = client.PostAsync("https://localhost:44396/Documentation/All?pageNumber=0&pageSize=10", httpContent).Result;
if (response.IsSuccessStatusCode)
{
response = await response.Content.ReadAsStringAsync();
}
}
Upvotes: 1
Reputation: 7575
Something like this :
try
{
string username = "adm", password = "123456";
string payload = "http://192.168.2.1/apply.cgi/?_ajax=1&_web_cmd=%21%0Aio%20output%201%20on%0A";
HttpClient client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = await client.GetAsync(payload);
HttpContent content = response.Content;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Auth error");
}
else
{
Console.WriteLine(response.StatusCode);
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
Upvotes: 1