从C#登录Garmin Connect

时间:2014-03-14 21:47:32

标签: c# http garmin

我有一个代码可以登录GarminConnect.com,但是garmin选择更改他们的登录过程,因此我的代码不再工作了,而且我又失去了如何让它再次运行。

我通常不会开发网络通信应用程序,所以我不应该对我如何继续让它再次运行起作用。

这就是我现在所拥有的:

public class SessionService
{
    private const string SignInUrl = @"https://connect.garmin.com/en-US/signin";
    private const string DashboardUrl = @"http://connect.garmin.com/dashboard";

    public Session Session { get; private set; }

    public bool SignIn(string userName, string password)
    {
        try
        {
            Session = new Session();
            GetSignInPage(Session.Cookies);

            var signInResponse = PostSignInRequest(Session.Cookies, userName, password);

            if (IsDashboardUri(signInResponse.ResponseUri))
                return true;
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error signing in. {0}", ex.Message);
        }

        return false;
    }

    public void SignOut()
    {
        var request = HttpUtils.CreateRequest(BuildSignOutUrl(), Session.Cookies);
        request.GetResponse();
    }

    private static string BuildSignOutUrl()
    {
        var queryString = HttpUtils.CreateQueryString();
        queryString.Add("actionMethod", "page/home/dashboard.xhtml:identity.logout");
        queryString.Add("cid", "");
        return String.Format("{0}?{1}", DashboardUrl, queryString);
    }

    private static void GetSignInPage(CookieContainer cookies)
    {
        var request = HttpUtils.CreateRequest(DashboardUrl, cookies);
        request.GetResponse();
    }

    private static HttpWebResponse PostSignInRequest(CookieContainer cookies, string userName, string password)
    {
        var formBinaryData = BuildSignInFormData(userName, password);

        var request = HttpUtils.CreateRequest(SignInUrl, cookies);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.WriteBinary(formBinaryData);
        return (HttpWebResponse)request.GetResponse();
    }

    private static byte[] BuildSignInFormData(string userName, string password)
    {
        var formParams = HttpUtils.CreateQueryString();
        formParams.Add("login", "login");
        formParams.Add("login:loginUsernameField", userName);
        formParams.Add("login:password", password);
        formParams.Add("login:signInButton", "Sign In");
        formParams.Add("javax.faces.ViewState", "j_id1");
        return Encoding.UTF8.GetBytes(formParams.ToString());
    }

    private static bool IsDashboardUri(Uri uri)
    {
        return uri.ToString().StartsWith(DashboardUrl);
    }
}

我希望有人能够指出我如何使这项工作正确的方向

1 个答案:

答案 0 :(得分:0)

Garmin似乎是通过JS呈现iframe。我怀疑做一个基本的表单帖子将处理这个因为Javascript需要运行来构建DOM元素。您应该联系Garmin以使用他们的API。