Send POST data to URL with CefSharp C#
Asked Answered
G

1

9

Im trying to work out how to send post data directly to a url with cefsharp. Here is an example of what I want to send:

var values = new Dictionary<string, string>
{
     { "thing1", "hello" },
     { "thing2", "world" }
};
FormUrlEncodedContent content = new FormUrlEncodedContent(values);

Which will create thing1=hello&thing2=world I want to send this POST data to the url http://example.com/mydata.php using the existing browser with cefsharp.

From what I can see

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

Has no way to attach POST data, is there a way I can do this?

Basically I need to keep the same cookies that the browser already has, so if there is another way to do this for example using HttpWebRequest with the cefsharp ChromiumWebBrowser cookies then syncing them again after that request, that would also work, but i'm not sure if that is possible.

Gromwell answered 24/2, 2017 at 22:22 Comment(1)
cefsharp.github.io/api/55.0.0/html/…Stroud
V
12

You can issue a POST using CefSharp via the LoadRequest method of the IFrame interface.

For example, you can make an extension method that implements the equivalent of Microsoft's System.Windows.Forms.WebBrowser.Navigate(..., byte[] postData, string additionalHeaders) with something like

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);
    }
Vas answered 25/5, 2017 at 19:36 Comment(3)
It's not necessary to inherit from ChromiumWebBrowser. You could easily make this an extension method. Converting your data to a string is actually going to then use the default encoder to convert it back to a byte array, your using github.com/cefsharp/CefSharp/blob/… when you should set the data directly.Stroud
How do I set the data directly?Vas
like this: request.InitializePostData(); var postData = request.PostData; var element = postData.CreatePostDataElement(); element.Bytes = postDataBytes; request.PostData.AddElement(element); ?Vas

© 2022 - 2024 — McMap. All rights reserved.