使用CefSharp的C#向URL发送POST数据

9
我将尝试解释如何使用CefSharp直接向URL发送POST数据。 以下是我要发送的示例:
var values = new Dictionary<string, string>
{
     { "thing1", "hello" },
     { "thing2", "world" }
};
FormUrlEncodedContent content = new FormUrlEncodedContent(values);

我希望将以下内容作为POST数据发送到http://example.com/mydata.php,数据内容为thing1=hello&thing2=world,并使用已有的cefsharp浏览器进行操作。

据我所见:

browser.Load("http://example.com/mydata.php");

无法附加POST数据,有没有其他方法可以实现呢?

基本上我需要保留浏览器已经有的相同cookie,因此如果有另一种方法可以使用HttpWebRequest和cefsharp ChromiumWebBrowser cookie一起使用,然后再次同步该请求,那也可以,但我不确定是否可能。


http://cefsharp.github.io/api/55.0.0/html/M_CefSharp_IFrame_LoadRequest.htm - amaitland
1个回答

12

使用 CefSharp,您可以通过 IFrame 接口的 LoadRequest 方法发布 POST 请求。

例如,您可以编写一个扩展方法来实现类似于 Microsoft 的 System.Windows.Forms.WebBrowser.Navigate(..., byte[] postData, string additionalHeaders) 的等效操作:

public void Navigate(this IWebBrowser browser, string url, byte[] postDataBytes, string contentType)
    {
        IFrame frame = browser.GetMainFrame();
        IRequest request = frame.CreateRequest();

        request.Url = url;
        request.Method = "POST";

        request.InitializePostData();
        var element = request.PostData.CreatePostDataElement();
        element.Bytes = postDataBytes;
        request.PostData.AddElement(element);

        NameValueCollection headers = new NameValueCollection();
        headers.Add("Content-Type", contentType );
        request.Headers = headers;

        frame.LoadRequest(request);
    }

不需要从ChromiumWebBrowser继承。你可以轻松地将其变成扩展方法。将数据转换为字符串实际上会使用默认编码器将其转换回字节数组,你正在使用https://github.com/cefsharp/CefSharp/blob/cd934267c65f494ceb9ee75995cd2a1ca0954543/CefSharp/PostDataExtensions.cs#L128,而应该直接设置数据。 - amaitland
我该如何直接设置数据? - jwezorek
request.InitializePostData(); var postData = request.PostData; var element = postData.CreatePostDataElement(); element.Bytes = postDataBytes; request.PostData.AddElement(element); 请求.初始化Post数据(); var postData = 请求.Post数据; var element = postData.创建Post数据元素(); element.Bytes = postDataBytes; 请求.Post数据.添加元素(元素); - jwezorek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接