发布数据

时间:2016-08-28 10:34:43

标签: c# post system.web

我的请求方法

    /// <summary>
    /// The formal method to use HTTPWebRequests.
    /// I got the headers out of Fiddler. I highly recommend this tool to follow HTTPWebRequests.
    /// Some Headers are unnecessary but i will use them for a natural-looking HTTPWebRequests.
    /// </summary>
    /// <param name="inpUrl">URL of the HTTPWebRequest.</param>
    /// <param name="inpMethod">Method of the HTTPWebRequest.
    /// Example: "POST", "GET", "PUT",...</param>
    /// <param name="inpReferer">The Referer of the URL. Sometimes its needed.</param>
    /// <param name="inpHost">The Host of the request.</param>
    /// <param name="inpAccept">Accept format of the request.</param>
    /// <param name="inpNvc">Data which will be wrote if you will do a "Post".</param>
    /// <param name="inpXml">If Ajax, then this is required.</param>
    /// <param name="autoRedirect">Auto-Redirect.</param>
    /// <returns>A HttpWebResponse of the request.</returns>
    private HttpWebResponse Request(string inpUrl, string inpMethod, string inpReferer, string inpHost, string inpAccept, NameValueCollection inpNvc, bool inpXml, bool autoRedirect)
    {
        var request = (HttpWebRequest)WebRequest.Create(inpUrl);
        request.Accept = inpAccept;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
        request.Timeout = 20000;
        request.Headers.Add("Accept-Language", "de,en-US;q=0.7,en;q=0.3");
        request.AllowAutoRedirect = autoRedirect;
        request.CookieContainer = _cookies;
        request.Method = inpMethod;
        //Volatile variables

        if (inpHost != "")
        {
            request.Host = inpHost;
        }

        if (inpReferer != "")
        {
            request.Referer = inpReferer;
        }
        if (inpXml)
        {
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("X-Prototype-Version", "1.7");
            request.Headers.Add("Cache-Control", "no-cache");
            request.Headers.Add("Pragma", "no-cache");
        }

        if (inpMethod != "POST") return request.GetResponse() as HttpWebResponse;
        var dataString = (inpNvc == null ? null : string.Join("&", Array.ConvertAll(inpNvc.AllKeys, key =>
            HttpUtility.UrlEncode(key) +"=" + HttpUtility.UrlEncode(inpNvc[key])
            )));
        if (dataString == null) return request.GetResponse() as HttpWebResponse;
        var dataBytes = Encoding.UTF8.GetBytes(dataString);
        request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
        request.ContentLength = dataBytes.Length;
        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(dataBytes, 0, dataBytes.Length);
        }
        return request.GetResponse() as HttpWebResponse;
    }

我正常使用,但是今天。当我试图将新订单发布到商店网站时,它给我带来了错误。我已经在网站上登录了程序,之后我将cookie添加到容器中,但程序抛出系统。 Web.Exception 401 //授权错误。

我试图请求https://backpack.tf/classifieds/sell/4219201808 Html表单= http://pastebin.com/5xLp2jSU 我的发布订单方法=

    public void PostOrder(string inpUrl, string metal, int key, string message, bool tradeOffer, bool buyOut, string tradeOfferUrl)
    {
        var data = new NameValueCollection
        {
            {"user-id", _userId},
            {"currencies[metal]", metal},
            {"currencies[keys]", key.ToString()},
            {"details", message}
        };
        if (tradeOffer)
        {
            if (tradeOfferUrl != string.Empty)
            {
                data.Add("offers", "1");
                data.Add("tradeoffers_url", tradeOfferUrl);
            }
        }
        else
        {
            data.Add("offers", "0");
            data.Add("tradeoffers_url", "");
        }
        data.Add("buyout", buyOut ? "1" : "0");
        const string accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        const string referer = "http://backpack.tf/classifieds/buy/Strange/Rust%20Botkiller%20Scattergun%20Mk.I/Tradable/Craftable";
        const string host = "backpack.tf";
        using (var httpResponse = Request(inpUrl, "POST", referer, host, accept, data, false, false))
        {
            _cookies.Add(httpResponse.Cookies);
        }
    }

我的登录方式

public void DoLogin(string inpSteamUserName, string inpSteamPassword, string inpSharedSecret = "")
    {
        _cookiePath += inpSteamUserName + ".auth";
        var responseString = GetIndex();
        SetUserId(responseString);
        var location = PostLogin();
        SetOpenIdParams(location);
        // Now do Steam Login.
        dynamic steamResult = DoSteamLogin(inpSteamUserName, inpSteamPassword, inpSharedSecret);
        if (steamResult == null) return;
        PostTransfer(steamResult.transfer_parameters.steamid.ToString(),
            steamResult.transfer_parameters.token.ToString(),
            steamResult.transfer_parameters.auth.ToString(),
            steamResult.transfer_parameters.remember_login.ToString(),
            steamResult.transfer_parameters.token_secure.ToString());
        location = OpenIdLogin();
        location = GetBackpackCookies(location);
        if (location == "/" || location == "https://backpack.tf/")
        {
            // Verify Cookies.
            const string url = "https://backpack.tf/";
            const string method = "GET";
            const string host = "backpack.tf";
            const string accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            FetchRequest(url, method, "", host, accept, null, false, true);
        }
        Log.Success("Bot logged in to backpack.tf");

 private dynamic DoSteamLogin(string username, string password, string inpSharedSecret)
    {
        dynamic returnObject;
        var data = new NameValueCollection { { "username", username } };
        const string accept = "text/javascript, text/html, application/xml, text/xml, */*";
        const string referer = "https://steamcommunity.com/openid/login?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=checkid_setup&openid.return_to=http%3A%2F%2Fbackpack.tf%2Flogin&openid.realm=http%3A%2F%2Fbackpack.tf&openid.ns.sreg=http%3A%2F%2Fopenid.net%2Fextensions%2Fsreg%2F1.1&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select";
        const string host = "steamcommunity.com";
        var response = FetchRequest("https://steamcommunity.com/login/getrsakey", "POST", referer, host, accept,
            data, true, false);
        var rsaJson = JsonConvert.DeserializeObject<GetRsaKeyBackPack>(response);

        // Validate
        if (!rsaJson.Success)
        {
            return null;
        }

        //RSA Encryption
        var rsa = new RSACryptoServiceProvider();
        var rsaParameters = new RSAParameters
        {
            Exponent = HexToByte(rsaJson.PublickeyExp),
            Modulus = HexToByte(rsaJson.PublickeyMod)
        };

        rsa.ImportParameters(rsaParameters);

        var bytePassword = Encoding.ASCII.GetBytes(password);
        var encodedPassword = rsa.Encrypt(bytePassword, false);
        var encryptedBase64Password = Convert.ToBase64String(encodedPassword);

        SteamResultBackPack loginJson = null;
        CookieCollection cookieCollection;
        var steamGuardText = "";
        var steamGuardId = "";
        do
        {
            Log.Success("SteamWeb: Logging In...");

            var captcha = loginJson != null && loginJson.CaptchaNeeded;
            var steamGuard = loginJson != null && loginJson.EmailauthNeeded;

            var time = Uri.EscapeDataString(rsaJson.Timestamp);
            var capGid = "-1";
            if (loginJson != null)
            {
                capGid = Uri.EscapeDataString(loginJson.CaptchaGid);
            }
            data = new NameValueCollection { { "password", encryptedBase64Password }, { "username", username } };

            // Captcha
            var capText = "";
            if (captcha)
            {
                Console.WriteLine("SteamWeb: Captcha is needed.");
                System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.CaptchaGid);
                Console.WriteLine("SteamWeb: Type the captcha:");
                capText = Uri.EscapeDataString(Console.ReadLine());
            }

            data.Add("captchagid", captcha ? capGid : "");
            data.Add("captcha_text", captcha ? capText : "");
            if (inpSharedSecret != "")
            {
                var twoFactorGenerator = new SteamTwoFactorGenerator
                {
                    SharedSecret = inpSharedSecret
                };
                data.Add("twofactorcode", twoFactorGenerator.GenerateSteamGuardCodeForTime());
            }
            else
            {
                data.Add("twofactorcode", "");
            }

            data.Add("remember_login", "false");

            // Captcha end

            // SteamGuard
            if (steamGuard)
            {
                Console.WriteLine("SteamWeb: SteamGuard is needed.");
                Console.WriteLine("SteamWeb: Type the code:");
                steamGuardText = Uri.EscapeDataString(Console.ReadLine());
                steamGuardId = loginJson.Emailsteamid;
                data.Add("loginfriendlyname", "machine1");
            }
            else
            {
                data.Add("loginfriendlyname", inpSharedSecret);
            }

            data.Add("emailauth", steamGuardText);
            data.Add("Emailsteamid", steamGuardId);
            data.Add("donotcache", "1440170894227");

            // SteamGuard end

            data.Add("rsatimestamp", time);

            using (var webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", referer, host, accept, data, true, false))
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                using (var reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    var json = reader.ReadToEnd();
                    returnObject = JObject.Parse(json);
                    loginJson = JsonConvert.DeserializeObject<SteamResultBackPack>(json);
                    cookieCollection = webResponse.Cookies;
                }
            }
        } while (loginJson.CaptchaNeeded || loginJson.EmailauthNeeded);


        if (loginJson.Success)
        {
            foreach (Cookie cookie in cookieCollection)
            {
                _cookies.Add(cookie);
            }
            return returnObject;
        }
        Console.WriteLine("SteamWeb Error: " + loginJson.Message);
        return null;
    }

我的请求方法仅在发布新订单时抛出错误。

修正:它是登录方法。

0 个答案:

没有答案