Отправить POST-запрос через Awesomium - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте, господа! Нужен пример отправки post запроса через Awesomium, например, по нажатию кнопки. Есть url, на который нужно отправлять запрос и допустим поля login и password. Как это реализовать? Для примера что я имею ввиду - в WebBrowser это делается так:
Листинг программы
  1. string data = "email=vasya&pass=123456789";
  2. webBrowser1.Navigate("http://test1.ru/login.php", "_self", System.Text.Encoding.ASCII.GetBytes(data), "content-type:application/x-www-form-urlencoded");
Нашел решение!!!

1.

Добавляем новый файл класса к проекту, называем его, например, CustomInterceptor.cs и вставляем в него это:
Листинг программы
  1. // CRI.CustomResourceInterceptor
  2. //
  3. // Author: Garison E Piatt
  4. // Contact: {removed}
  5. // Created: 11/17/14
  6. // Version: 1.0.0
  7. //
  8. // Apparently, when Awesomium was first created, the programmers did not understand that someone would
  9. // eventually want to post data from the application. So they made it incredibly difficult to upload
  10. // POST parameters to the remote web site. We have to jump through hoops to get that done.
  11. //
  12. // This module provides that hoop-jumping in a simple-to-understand fashion. We hope. It overrides
  13. // the current resource interceptor (if any), replacing both the OnRequest and OnFilterNavigation
  14. // methods (we aren't using the latter yet).
  15. //
  16. // It also provides settable parameters. Once this module is attached to the WebCore, it is *always*
  17. // attached; therefore, we can simply change the parameters before posting to the web site.
  18. //
  19. // File uploads are currently unhandled, and, once handled, will probably only upload one file. We
  20. // will deal with that issue later.
  21. //
  22. // To incoroprate this into your application, follow these steps:
  23. // 1. Add this file to your project. You know how to do that.
  24. // 2. Edit your MainWindow.cs file.
  25. // a. At the top, add:
  26. // using CRI;
  27. // b. inside the main class declaration, near the top, add:
  28. // private CustomResourceInterceptor cri;
  29. // c. In the MainWindow method, add:
  30. // WebCore.Started += OnWebCoreOnStarted;
  31. // cri = new CustomResourceInterceptor();
  32. // and (set *before* you set the Source value for the Web Control):
  33. // cri.Enabled = true;
  34. // cri.Parameters = String.Format("login={0}&password={1}", login, pw);
  35. // (Choose your own parameters, but format them like a GET query.)
  36. // d. Add the following method:
  37. // private void OnWebCoreOnStarted(object sender, CoreStartEventArgs coreStartEventArgs) {
  38. // WebCore.ResourceInterceptor = cri;
  39. // }
  40. // 3. Compile your application. It should work.
  41. using System;
  42. using System.Runtime.InteropServices;
  43. using System.Text;
  44. using Awesomium.Core;
  45. using Awesomium.Windows.Forms;
  46.  
  47. namespace CRI
  48. {
  49. //* CustomResourceInterceptor
  50. // This object replaces the standard Resource Interceptor (if any; we still don't know) with something
  51. // that allows posting data to the remote web site. It overrides both the OnRequest and OnFilterNavigation
  52. // methods. Public variables allow for run-time configuration.
  53. public class CustomResourceInterceptor : IResourceInterceptor
  54. {
  55. // Since the default interceptor remains overridden for the remainder of the session, we need to disable
  56. // the methods herein unless we are actually using them. Note that both methods are disabled by default.
  57. public bool RequestEnabled = false;
  58. public bool FilterEnabled = false;
  59. // These are the parameters we send to the remote site. They are empty by default; another safeguard
  60. // against sending POST data unnecessarily. Currently, both values allow for only one string. POST
  61. // variables can be combined (by the caller) into one string, but this limits us to only one file
  62. // upload at a time. Someday, we will have to fix that. And make it backward-compatible.
  63. public String Parameters = null;
  64. public String FilePath = null;
  65. /** OnRequest
  66. ** This ovverrides the default OnRequest method of the standard resource interceptor. It receives
  67. ** the resource request object as a parameter.
  68. **
  69. ** It first checks whether or not it is enabled, and returns NULL if not. Next it sees if any
  70. ** parameters are defined. If so, it converst them to a byte stream and appends them to the request.
  71. ** Currently, files are not handled, but we hope to add that someday.
  72. */
  73. public ResourceResponse OnRequest(ResourceRequest request)
  74. {
  75. // We do nothing at all if we aren't enabled. This is a stopgap that prevents us from sending
  76. // POST data with every request.
  77. if (RequestEnabled == false) return null;
  78. // If the Parameters are defined, convert them to a byte stream and append them to the request.
  79. if (Parameters != null)
  80. {
  81. var str = Encoding.Default.GetBytes(Parameters);
  82. var bytes = Encoding.UTF8.GetString(str);
  83. request.AppendUploadBytes(bytes, (uint)bytes.Length);
  84. }
  85. // If either the parameters or file path are defined, this is a POST request. Someday, we'll
  86. // figure out how to get Awesomium to understand Multipart Form data.
  87. if (Parameters != null || FilePath != null)
  88. {
  89. request.Method = "POST";
  90. request.AppendExtraHeader("Content-Type", "application/x-www-form-urlencoded"); //"multipart/form-data");
  91. }
  92. // Once the data has been appended to the page request, we need to disable this process. Otherwise,
  93. // it will keep adding the data to every request, including those that come from the web site.
  94. RequestEnabled = false;
  95. Parameters = null;
  96. FilePath = null;
  97. return null;
  98. }
  99.  
  100. /** OnFilterNavigation
  101. ** Not currently used, but needed to keep VisualStudio happy.
  102. */
  103. public bool OnFilterNavigation(NavigationRequest request)
  104. {
  105. return false;
  106. }
  107. }
  108. }

2.

В основном классе добавляем
Листинг программы
  1. using CRI;
и перед InitializeComponent(); добавляем
Листинг программы
  1. WebCore.Started += OnWebCoreOnStarted;
  2. cri = new CustomResourceInterceptor();

3.

далее в нашем классе вставляем объявленную функцию
Листинг программы
  1. private void OnWebCoreOnStarted(object sender, CoreStartEventArgs coreStartEventArgs)
  2. {
  3. WebCore.ResourceInterceptor = cri;
  4. }

4.

и там где нужно отправлять post-запрос делаем примерно так:
Листинг программы
  1. cri.RequestEnabled = true;
  2. cri.Parameters = String.Format("login={0}&password={1}", login, pw);
  3. WebControl1.Source = new Uri(my_post_url); // где my_post_url - адрес, на который отправляются post-данные.
Всё отлично работает!

Решение задачи: «Отправить POST-запрос через Awesomium»

textual
Листинг программы
  1.         string Get(string url)
  2.         {
  3.             cri.RequestEnabled = false;
  4.             webControl1.Source = new Uri(url);
  5.             while (webControl1.IsLoading)
  6.                 Application.DoEvents();
  7.             return webControl1.HTML;
  8.         }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 3.5 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут