function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
星融 潘 6星融 潘 6 

How to use cookies in Apex?

Backgroud: I need access SAP from salesforce. SAP server is in  company intranet. Salesforce cloud is in outer net.
There is a gateway between SAP server and Salesforce cloud.
So first,I need a http request to login gateway with company's username and  password. The the gateway will respones 3 cookies.
I should include  these 3 cookies when I access the sap SOAP webservice.
I'm able to access SAP SOAP webservice in .Net as below.
//Creat request to login gateway
            System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create("gateway/login");
            String PostString = "user=myusername&password=mypassword&btn_login=Logn-On&idpid=at_hp";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] buffer = encoding.GetBytes(PostString);
            request.AllowAutoRedirect = false;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.CookieContainer = new CookieContainer();
            Stream reqstr = request.GetRequestStream();
            reqstr.Write(buffer,0,buffer.Length);
            reqstr.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//get the respones cookies
            CookieCollection mycookies = response.Cookies;
// Create sap SOAP webservice
            Z_WEBSERVICESService SAPWSDL = new Z_WEBSERVICESService();
// use the cookies
            SAPWSDL.CookieContainer = new CookieContainer();
            SAPWSDL.CookieContainer.Add(mycookies[0]);
            SAPWSDL.CookieContainer.Add(mycookies[1]);
            SAPWSDL.CookieContainer.Add(mycookies[2]);
//set the credential
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential();
            cred.UserName = "SAPusername";
            cred.Password = "SAPpassword";
            SAPWSDL.Credentials = cred;
//access SAP webservice.
            string xx = SAPWSDL.Z_WEBSERVICES();
I have some qustion about how to convert this code to apex.
1 In Apex, how to use cookies?
2 how to set AllowAutoRedirect = false? If Redirect,I can't get respones with cookies.
3 When use SOAP in Apex,is there a way to set cookies and credential.

Best Answer chosen by 星融 潘 6
Ramu_SFDCRamu_SFDC
The below articles might help

http://developer.force.com/cookbook/recipe/storing-form-field-values-with-the-apex-cookie-class
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_sites_cookie.htm
http://salesforce.stackexchange.com/questions/4894/how-is-a-cookie-constructed