KeepAlive in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Contrarian2
    Junior Member
    • Jun 2012
    • 9

    #1

    KeepAlive in C#

    Finally worked out how to log in and get a session token with API-NG.

    Could someone show me how to use Keep Alive? Preferably with the HttpWebRequest class.

    I tried this (adapting a login example given by someone on this forum):

    string uri = string.Format("https://identitysso.betfair.com/api/keepAlive");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
    req.Accept = "application/json";
    req.Headers.Add("X-Authentication", sessionToken);
    req.Method = "POST";
    req.Timeout = 5000;

    WebResponse resp = req.GetResponse();

    But it doesn't seem to work.

    Thanks.
  • Contrarian2
    Junior Member
    • Jun 2012
    • 9

    #2
    Or perhaps if someone could just tell me whether or not this address is correct:

    https://identitysso.betfair.com/api/keepAlive

    I assume it's wrong.

    Thanks.

    Comment

    • Tipmanager1
      Junior Member
      • Sep 2013
      • 34

      #3
      you should add the application key aswell in your request.

      so something like this:
      req.Headers.Add("X-Application", APPKEY);

      Comment

      • Contrarian2
        Junior Member
        • Jun 2012
        • 9

        #4
        Thanks Tipmanager1 but it still doesn't work.

        I think the application key is optional in keep alive requests.

        Comment

        • gus
          Senior Member
          • Jan 2009
          • 134

          #5
          Dunno much about c#, but, looking at the code, I'd have thought that just in terms of consistency, if
          req.Headers.Add("X-Authentication", sessionToken);
          is the correct syntax, then
          req.Accept = "application/json";

          should be
          req.Headers.Add("Accept", "application/json");

          Comment

          • Peter Simple
            Junior Member
            • Aug 2009
            • 32

            #6
            req.Headers.Add("Accept", "application/json");
            That will lead to an error in .net because "req.Accept" is already the "standart" header.

            I have tested the "KeepAlive" function andt did not get an json message as return but also no error message. I did not care about it because it seems that a token lasts more than 20 minutes - at least now.

            Comment

            • Contrarian2
              Junior Member
              • Jun 2012
              • 9

              #7
              Thanks Peter.

              Could you show me the code that you used for KeepAlive?

              It's a bit annoying, because I"m running bots using the API-NG, but I'm still having to manage the session using the old API, because I don't know how to keep it alive with the new one.

              Comment

              • davecon
                Junior Member
                • Dec 2010
                • 86

                #8
                Hi Suppose you just need to do this But Why bother if your bot is surely going to make a market call at least once every 20 mins anyway?
                Hope this helps anyway Dave
                Code:
                  Sub KeepAlive(SessToken As String, Optional AppKey As String = "")
                        Dim Url As String = " https://identitysso.betfair.com/api/keepAlive"
                        Dim request As WebRequest = Nothing
                        Dim response As WebResponse = Nothing
                        Dim strResponseStatus As String = ""
                        Try
                            request = WebRequest.Create(New Uri(Url))
                            request.Method = "POST"
                            request.ContentType = "application/json-rpc"
                            request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
                            request.Headers.Add("X-Authentication", SessToken)
                            If AppKey <> "" Then
                                request.Headers.Add("X-Application", AppKey)
                            End If
                            '~~> Get the response.
                            response = request.GetResponse()
                            '~~> Display the status below 
                            strResponseStatus = "Status is " & CType(response, HttpWebResponse).StatusDescription
                        Catch ex As Exception
                            MsgBox("CreateRequest Error" & vbCrLf & ex.Message)
                        End Try
                        MsgBox(strResponseStatus)
                        '~~~Clean Up
                        response.Close()
                    End Sub '
                Or I used a Converter for C#
                Code:
                public void KeepAlive(string SessToken, string AppKey = "")
                {
                	string Url = " https://identitysso.betfair.com/api/keepAlive";
                	WebRequest request = null;
                	WebResponse response = null;
                	string strResponseStatus = "";
                	try {
                		request = WebRequest.Create(new Uri(Url));
                		request.Method = "POST";
                		request.ContentType = "application/json-rpc";
                		request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8");
                		request.Headers.Add("X-Authentication", SessToken);
                		if (!string.IsNullOrEmpty(AppKey)) {
                			request.Headers.Add("X-Application", AppKey);
                		}
                		//~~> Get the response.
                		response = request.GetResponse();
                		//~~> Display the status below 
                		strResponseStatus = "Status is " + ((HttpWebResponse)response).StatusDescription;
                	} catch (Exception ex) {
                		Interaction.MsgBox("CreateRequest Error" + Constants.vbCrLf + ex.Message);
                	}
                	Interaction.MsgBox(strResponseStatus);
                	//~~~Clean Up
                	response.Close();
                }

                Comment

                • Contrarian2
                  Junior Member
                  • Jun 2012
                  • 9

                  #9
                  Thanks for that Dave. Works perfectly.

                  Comment

                  • chi
                    Junior Member
                    • Jul 2013
                    • 1

                    #10
                    Json keepAlive using http Client
                    1. Use System.Net.HttpWebRequest instead of System.Net.WebRequest. This class allows changing property relating to "Accept" parameter that is required by API-NG.
                    1. Use System.Io.StreamReader to get the response content.

                    C# code
                    Code:
                    public void KeepAlive2(string SessToken, string AppKey)
                    {
                        string Url = "https://identitysso.betfair.com/api/keepAlive";
                        [COLOR="SeaGreen"]System.Net.HttpWebRequest[/COLOR] request = null;
                        [COLOR="SeaGreen"]System.Net.HttpWebResponse[/COLOR] response = null;
                        string strResponseContent = "";
                        try 
                        {
                            request = [COLOR="Green"]System.Net.HttpWebRequest[/COLOR].Create(new Uri(Url));
                            request.Accept = "application/json"; [COLOR="Purple"]// Tells API-NG to respond in Json not Html[/COLOR]
                            request.Method = "POST";
                            request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8");
                            request.Headers.Add("X-Authentication", SessToken);
                            if (!string.IsNullOrEmpty(AppKey)) equest.Headers.Add("X-Application", AppKey);
                            // Get the response using io stream
                            using ([COLOR="Green"]System.Net.HttpWebResponse[/COLOR] wr = request.GetResponse())
                            {
                                using ([COLOR="Green"]System.Io.StreamReader[/COLOR] sr = new [COLOR="SeaGreen"]System.Io.StreamReader[/COLOR](wr.GetResponseStream()))
                                {
                                    strResponseContent = sr.ReadToEnd().ToString;
                                    sr.Close();
                                }
                                wr.Close();
                            }
                            Console.WriteLine(strResponseContent); 
                        } 
                        catch (Exception ex) 
                        {
                            Console.WriteLine("Error: " + Environment.NewLine + ex.Message);
                        }
                        // Expect to print out {"token":"4bnwldH;gf+jemndUIjmndGbCc=","product":"Your Product ID","status":"SUCCESS","error":""}
                    }
                    VB code:
                    Code:
                    Public Sub KeepAlive2(SessToken As String, AppKey As String)
                        Dim Url As String = "https://identitysso.betfair.com/api/keepAlive"
                        Dim request As [COLOR="Green"]System.Net.HttpWebRequest[/COLOR] = Nothing
                        Dim response As [COLOR="Green"]System.Net.HttpWebResponse[/COLOR] = Nothing
                        Dim strResponseContent As String = ""
                        Try
                            request = [COLOR="SeaGreen"]System.Net.HttpWebRequest[/COLOR].Create(New Uri(Url))
                            With request
                                .Accept = "application/json" [COLOR="DarkRed"]' Tells API-NG to respond in Json not Html[/COLOR]
                                .Method = "POST"
                                .Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
                                .Headers.Add("X-Authentication", SessToken)
                                If Not String.IsNullOrEmpty(AppKey) Then .Headers.Add("X-Application", AppKey)
                            End With
                            ' Get response using io stream
                            Using wr As [COLOR="Green"]System.Net.HttpWebResponse[/COLOR] = request.GetResponse()
                                Using sr As New [COLOR="Green"]System.IO.StreamReader[/COLOR](wr.GetResponseStream())
                                    strResponseContent = sr.ReadToEnd().ToString
                                    sr.Close()
                                End Using
                                wr.Close()
                            End Using
                            Console.WriteLine(strResponseContent)
                        Catch ex As Exception
                            Console.WriteLine("Error: " + Environment.NewLine + ex.Message)
                        End Try
                        ' Expect to print out {"token":"4bnwldH;gf+jemndUIjmndGbCc=","product":"Your Product ID","status":"SUCCESS","error":""}
                    End Sub
                    Last edited by chi; 06-12-2014, 04:35 PM. Reason: Correction of minor error

                    Comment

                    Working...
                    X