1

我正在尝试在使用 Web 服务的 c# 应用程序中使用 cookie。登录方法有效,但是当我尝试使用更改密码方法时,它会给出 401 状态码。

HTTP.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace RemoteSynchronizer
{
    class HTTP
    {
        HttpWebRequest request = null;
        public static CookieContainer contain;


        public HTTP()
        {
            contain = new CookieContainer();
        }

        public int postData(string url, StringBuilder data)
        {

            int status;
            Uri address = new Uri(url);

            request = WebRequest.Create(address) as HttpWebRequest;
            request.CookieContainer = contain;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.KeepAlive = true;

            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            request.ContentLength = byteData.Length;

            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                status = (int)response.StatusCode;
            }


            return status;
        }


/// <summary>
/// /////////////////////////
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
/// 

        public int change(string url, StringBuilder data)
        {
            int status;
            Uri address = new Uri(url);

            request = WebRequest.Create(address) as HttpWebRequest;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.CookieContainer = contain;

            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            request.ContentLength = byteData.Length;

            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                status = (int)response.StatusCode;
            }

            return status;
        }
    }
}

如何保存 cookie 以便在其他课程中重复使用?

4

0 回答 0