簡體   English   中英

c#帶有基本身份驗證的http post請求

[英]c# http post request with basic authentication

我編寫了一個 python 函數,通過帶有基本身份驗證的 HTTP post 請求移動路由器的 IO 端口。 這工作正常。 但現在我想用 C# 實現 sam。

這是我的python函數:

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)

我已經嘗試過 NetWorkCredentials,但沒有成功。

像這樣的事情:

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

這是我使用基本身份驗證進行 POST 的方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM