HttpClient用于远程安全登录

时间:2018-05-28 05:54:04

标签: c#

我正在尝试以编程方式登录远程主机以在需要时更新设置。我的登录失败了404,这是我的代码:

public async void Go(string url)
{

    // Create a Uri:
    Uri uri = new Uri(url);

    // Create and configure ClientHandler:
    HttpClientHandler ClientHandler = new HttpClientHandler()
    {
        AllowAutoRedirect = true,
        AutomaticDecompression = DecompressionMethods.GZip,
        ClientCertificateOptions = ClientCertificateOption.Automatic,
        CookieContainer = new CookieContainer(),
        Credentials = null,
        MaxAutomaticRedirections = 7,
        MaxRequestContentBufferSize = 1024 * 2,
        PreAuthenticate = false,
        Proxy = new WebProxy(),
        UseCookies = true,
        UseDefaultCredentials = false,
        UseProxy = false
    };

    // Create a new HttpClient and parse in the ClientHandler:
    HttpClient client = new HttpClient(ClientHandler);

    // Get the Uri Async, required to get Cookies:
    string html = await client.GetStringAsync(uri);

    // Get the Cookies from the Cookie Container:
    CookieCollection collection = ClientHandler.CookieContainer.GetCookies(uri);

    // Attempt Login:
    html = await client.GetStringAsync(BuildUri(html)); // 404 occurs here.
    }

    private string GetToken(string html)
    {

        string look = "ajax_token: '";
        string to = "',";
        int StartIndex = html.IndexOf(look) + look.Length;

        html = html.Substring(StartIndex);
        int EndIndex = html.IndexOf(to);
        string token = html.Substring(0, EndIndex);

        return token;
    }

    private string BuildUri(string html)
    {

        string token = GetToken(html);

        string Parameters = "/ajax_token=" + token 
                          + "&action=" + "login" 
                          + "&username_login=" + Username 
                          + "&password_login=" + Password;

        // Concatinate Uri and Params;
        string URI = "https://www.crazydomains.com.au/ajax/top-shopping-cart" + Parameters;

        return (URI);
    }

我登录的Uri是:

https://www.crazydomains.com.au/

我正在尝试通过代码更新我的DNS A和MX记录作为我的IP更改。 使用Fiddler,Uri看起来是正确的,我正在建立POST。

https://www.crazydomains.com.au/ajax/top-shopping-cart/ajax_token=<TOKEN>&action=login&username_login=<USERNAME>&password_login=<PASSWORD>

我不明白为什么我得到404,Cookies看起来是正确和有效的,而且Uri和凭证看起来是正确的。如果有人可以指出我的问题,我做错了什么,我会非常感激!

编辑:我也尝试过:

// Get the Token:
string token = GetToken(html);

// Conf Params:
string Parameters = "ajax_token=" + token
                  + "&action=" + "login"
                  + "&username_login=" + Username
                  + "&password_login=" + Password;

// Post URI:
string PostURI = "https://www.crazydomains.com.au/ajax/top-shopping-cart/";

// Init Content:
HttpContent content = new StringContent(Parameters, Encoding.UTF8, "application/json");

// Attempt Login:
HttpResponseMessage response = await client.PostAsync(PostURI, content);

我仍然得到404; - (

0 个答案:

没有答案