使用 cookie 创建一个 WebRequest 并返回 HTML C#
本文关键字:WebRequest 返回 HTML 一个 创建 cookie 使用 | 更新日期: 2023-09-27 18:34:14
我正在尝试登录亚马逊卖家平台帐户,然后从订单页面返回 HTML(需要登录)。 我的流阅读器返回 null,所以我的代码一定有问题,或者我这样做的想法有缺陷。
在此代码的第一部分中,ConsoleReadline()
. 我正在发布我的用户名和密码,然后我收到一个cookie,它显示在控制台中,但我相信,当我尝试检索下一个URI字符串的HTML时,我的第二部分是错误的。
法典
using System;
using System.IO;
using System.Text;
using System.Net;
namespace HandleWebRequest
{
class Program
{
static void Main(string[] args)
{
string loginUri = "https://sellercentral.amazon.com/gp/homepage.html?";
string orderUri =
"https://sellercentral.amazon.com/gp/orders-v2/list/ref=ag_myo_wos3_home?byDate=shipDate&statusFilter=ItemsToShip&searchFulfillers=mfn&ignoreSearchType=1&searchType=OrderStatus&_encoding=UTF8&searchDateOption=preSelected&sortBy=OrderStatusDescending&shipSearchDateOption=noTimeLimit";
string username = "myusernmae";
string password = "mypassword";
string reqString = "username=" + username + "&password=" + password;
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
CookieContainer cc = new CookieContainer();
var request = (HttpWebRequest) WebRequest.Create(loginUri);
request.Proxy = null;
request.CookieContainer = cc;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestData.Length;
using (Stream s = request.GetRequestStream())
s.Write(requestData, 0, requestData.Length);
using (var response = (HttpWebResponse)request.GetResponse())
foreach (Cookie c in response.Cookies)
{
Console.WriteLine(c.Name + " = " + c.Value);
Console.WriteLine(c.Domain);
}
Console.ReadLine();
request = (HttpWebRequest) WebRequest.Create(orderUri);
request.CookieContainer = cc;
using (WebResponse response = request.GetResponse())
using (Stream s = response.GetResponseStream())
using (StreamReader sr = new StreamReader(s))
File.WriteAllText("code.html", sr.ReadToEnd());
System.Diagnostics.Process.Start("code.html");
}
}
}
response
是一个新对象;它不只是继承你放入request
的cookie容器。您需要将 cookie 从response.Cookies
输入到您的 CookieContainer 中,否则下一个请求将不会包含它们:
foreach (Cookie c in response.Cookies)
cc.Add(new Uri(this.m_HttpWebResponse.ResponseUri.Scheme + "://" + c.Domain), c);
request = (HttpWebRequest) WebRequest.Create(orderUri);
request.CookieContainer = cc;