gpt4 book ai didi

c# - 如何使用 WebBrowser 控件从发送 POST 数据中获取响应数据?

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:41 24 4
gpt4 key购买 nike

我想知道如何在使用 WebBrowser 控件的重载“Navigate”方法后获取响应数据。这是我正在做的一个例子:

wb.Navigate("https://live.xbox.com/en-US/Friends/List", "", Encoding.ASCII.GetBytes(post), "Content-Type: application/x-www-form-urlencoded\r\n");

这是将我的页面导航到第一个参数,但我不知道如何通过调用它来获取响应数据。我想要的结果也是响应的主体。有人可以帮帮我吗?我尝试使用 WebRequest 和 WebResponse 方式,但出于某种原因它们不允许我将用户登录到 Xbox Live 网站,导致我无法执行任何操作并出现 411 错误。不过,我希望能够使用 WebBrowser 执行此操作。但如果我不能,任何帮助将不胜感激。

最佳答案

您可以使用 webbrowser 控件使用虚假的 web 点击事件等登录(您似乎已经这样做了,+1)

然后您可以将 cookie 从 webbrowser 控件传输到 webrequest 来做更多理智的事情。您也可以缓存 cookie 以备后用

using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;

namespace Sample.Helpers {
public class NativeMethods {
public static CookieContainer GetUriCookieContainer(Uri uri) {
CookieContainer cookies = null;
int datasize = 8192 * 16; // Determine the size of the cookie
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(uri.ToString(), null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero)) {
if (datasize < 0)
return null;
cookieData = new StringBuilder(datasize); // Allocate stringbuilder large enough to hold the cookie
if (!InternetGetCookieEx(
uri.ToString(),
null, cookieData,
ref datasize,
InternetCookieHttponly,
IntPtr.Zero))
return null;
}
if (cookieData.Length > 0) {
cookies = new CookieContainer();
cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
}
return cookies;
}
[DllImport("wininet.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true)]
private static extern bool InternetGetCookieEx(string url, string cookieName, StringBuilder cookieData, ref int size, Int32 dwFlags, IntPtr lpReserved);
private const Int32 InternetCookieHttponly = 0x2000;

}
}

示例用法

var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.CookieContainer = Cookies;
//webRequest.Headers.Add(HeaderCollection);
webRequest.Timeout = 10000;
//webRequest.UserAgent = UserAgent;
webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
webRequest.Method = "POST";
byte[] postBytes;
if (postDataRaw != null) {
postBytes = Encoding.UTF8.GetBytes(postDataRaw);
}
webRequest.ContentLength = postBytes.Length;
using (var dataStream = webRequest.GetRequestStream()) {
dataStream.Write(postBytes, 0, postBytes.Length);
}
using (var response = webRequest.GetResponse()) {
var result = ((HttpWebResponse)response).StatusCode;
using (var responseStream = response.GetResponseStream()) {
using (var streamReader = new StreamReader(responseStream)) {
return streamReader.ReadToEnd();
}
}
}

关于c# - 如何使用 WebBrowser 控件从发送 POST 数据中获取响应数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18295237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com