我试图在我的c#应用程序中使用cookie,这是一个正在使用Web服务的应用程序。登录方法正在运行,但是当我尝试使用更改密码方法时,它会提供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以便在其他课程中重复使用?