c# - WebRequest HTTP POST with Cookie (port from curl script)

后端 未结 2 1490
清酒与你
清酒与你 2021-01-31 00:08

The IBM RTC RESTful api gives an example of a shell script for authenticating with the server:

COOKIES=./cookies.txt

USER=my_user
PASSWORD=my_password
HOST=\"ht         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 00:52

    I would suggest you try the following:

    public class WebClientEx : WebClient
    {
        private CookieContainer _cookieContainer = new CookieContainer();
    
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _cookieContainer;
            }
            return request;
        }
    }
    
    class Program
    {
        static void Main()
        {
            using (var client = new WebClientEx())
            {
                var response1 = client.DownloadString("https://myJazzServer.com:9092/jazz/authenticated/identity");
    
                var data = new NameValueCollection
                {
                    { "j_username", "myUser" },
                    { "j_password", "MyPass" },
                };
                var response2 = client.UploadValues("https://myJazzServer.com:9092/jazz/authenticated/j_security_check", data);
                Console.WriteLine(Encoding.Default.GetString(response2));
            }
        }
    }
    

    Also to simplify debugging you could activate tracing by putting this in your app.config:

    
    
      
        
          
            
              
            
          
        
    
        
          
        
    
        
      
    
    

    This will create a detailed log file of the network activity which might simplify debugging.

提交回复
热议问题