35

次のような単純なhtmlファイルがあります

<form action="http://www.someurl.com/page.php" method="POST">
   <input type="text" name="test"><br/>
   <input type="submit" name="submit">
</form>

編集:質問が十分に明確ではなかった可能性があります

上記のhtmlをファイルに貼り付け、IEで開き、ブラウザで送信した場合とまったく同じ方法でこのフォームを送信するC#コードを書きたいと思います。

4

6 に答える 6

31

これは、GET応答を受信するゲートウェイPOSTトランザクションで最近使用したサンプルスクリプトです。これをカスタムC#フォームで使用していますか?目的が何であれ、文字列フィールド(ユーザー名、パスワードなど)をフォームのパラメーターに置き換えるだけです。

private String readHtmlPage(string url)
   {

    //setup some variables

    String username  = "demo";
    String password  = "password";
    String firstname = "John";
    String lastname  = "Smith";

    //setup some variables end

      String result = "";
      String strPost = "username="+username+"&password="+password+"&firstname="+firstname+"&lastname="+lastname;
      StreamWriter myWriter = null;

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      objRequest.Method = "POST";
      objRequest.ContentLength = strPost.Length;
      objRequest.ContentType = "application/x-www-form-urlencoded";

      try
      {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(strPost);
      }
      catch (Exception e) 
      {
         return e.Message;
      }
      finally {
         myWriter.Close();
      }

      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      using (StreamReader sr = 
         new StreamReader(objResponse.GetResponseStream()) )
      {
         result = sr.ReadToEnd();

         // Close and clean up the StreamReader
         sr.Close();
      }
      return result;
   } 
于 2009-08-13T19:37:46.833 に答える
13

HTML ファイルが C# と直接対話することはありませんが、HTML ファイルであるかのように動作するように C# を記述できます。

たとえば、単純なメソッドを持つ System.Net.WebClient というクラスがあります。

using System.Net;
using System.Collections.Specialized;

...
using(WebClient client = new WebClient()) {

    NameValueCollection vals = new NameValueCollection();
    vals.Add("test", "test string");
    client.UploadValues("http://www.someurl.com/page.php", vals);
}

ドキュメントと機能の詳細については、MSDN ページを参照してください。

于 2009-08-13T19:16:50.487 に答える
5

これにはHttpWebRequestクラスを使用できます。

ここに例:

using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/
于 2009-08-13T19:11:19.550 に答える
2

クライアントのブラウザー内の別のアプリケーションに送信するフォームを作成するボタン ハンドラーが必要でした。この質問にたどり着きましたが、私のシナリオに合った答えが見つかりませんでした。これは私が思いついたものです:

      protected void Button1_Click(object sender, EventArgs e)
        {

            var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
  <input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" /> 
  <input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" /> 
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
            Response.Write(formPostText);
        }
于 2016-06-10T21:48:44.987 に答える
2
Response.Write("<script> try {this.submit();} catch(e){} </script>");
于 2009-11-19T08:50:54.903 に答える
1

MVC で同様の問題が発生しました (この問題が発生しました)。

WebClient.UploadValues() 要求からの文字列応答として FORM を受信して​​います。これを送信する必要があります。そのため、2 番目の WebClient または HttpWebRequest を使用できません。このリクエストは文字列を返しました。

using (WebClient client = new WebClient())
  {
    byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
    {
        { "test", "value123" }
    });

    result = System.Text.Encoding.UTF8.GetString(response);
  }

OPを解決するために使用できる私の解決策は、Javascriptの自動送信をコードの最後に追加し、 @Html.Raw() を使用してRazorページにレンダリングすることです。

result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);

かみそりコード:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

これが同じ状況に陥った人の助けになれば幸いです。

于 2015-05-28T09:18:19.207 に答える