简体   繁体   English

RestSharp响应对象没有cookie

[英]RestSharp no cookies on response object

I'm having an issue trying to write a bot for a simple browser game. 我在尝试为简单的浏览器游戏编写机器人时遇到了问题。

The game can be found here http://en.gladiatus.gameforge.com/game/ . 这个游戏可以在http://en.gladiatus.gameforge.com/game/找到。

The problem is that after I login, i need to get the cookie that is going to be used on future requests, but the RestResponse.Cookies is always empty. 问题是,在我登录后,我需要获取将在未来请求中使用的cookie,但RestResponse.Cookies始终为空。

Here's a working login code that should illustrate my problem. 这是一个工作的登录代码,应该说明我的问题。

public bool DoLogin() {
    var client = new RestClient("http://s2.en.gladiatus.gameforge.com"); //Server 2 on England.
    var request = new RestRequest( "/game/index.php?mod=start&submod=login", Method.POST );
    request.AddHeader( "Content-Type", "application/x-www-form-urlencoded" );
    request.AddParameter( "name", "bot_test"); //test account.
    request.AddParameter( "pass", "bot_test_pass");

    var response = client.Execute( request );

    var match = System.Text.RegularExpressions.Regex.Match( 
        response.Content, 
        "href=\"index\\.php\\?mod=news&submod=serverEvents&sh=([^&]*?)\"" );

    var _Successful = match.Success;

    MessageBox.Show( response.Cookies.Count.ToString() ); //Always 0

    if(!_Successful) //Could not login.
        return false;

    var _SecureHash = match.Groups[0].Value;

    return _Successful;
}

I tried everything that I know (which is not much) but I couldnt find what is wrong with my code. 我尝试了所有我知道的东西(这不是很多),但我找不到我的代码有什么问题。

Thanks for reading! 谢谢阅读!

You need to instantiate a CookieContainer on your RestClient before executing any requests: 在执行任何请求之前,您需要在RestClient上实例化CookieContainer

var client = new RestClient("http://s2.en.gladiatus.gameforge.com");
client.CookieContainer = new System.Net.CookieContainer();

Then make sure you re-use the same RestClient instance in subsequent requests, and the same cookies will be passed automatically with each request. 然后确保在后续请求中重复使用相同的RestClient实例,并且每个请求将自动传递相同的cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM