質問

提出し、HTTP POSTを使用してパラメータを渡すか、GET、私はパラメータが渡されているを発見したウェブデバッガを使用して形にスクリプトを呼び出す多くのサイトがあります。今私はC#で、私のWindowsアプリケーションを介して同じことをしたいです。どのように私は、このような機能を実現することができますか?

私は現在、C#でのHttpWebRequestとHttpWebResponseのクラスを使用しています。私はロードして動作するようにしようと、各ページに明示的なコードを記述する必要がありますようしかし、それは苦痛です。たとえば、私は、ユーザーがログインしたりしていない場合、私は識別しそれに基づいて、お返しにクッキーとページが送信されますされ、PHPページにユーザー名とパスワードを渡そうとレスポンスを取っています。

HttpWebRequest loginreq = createreq("http://www.indyarocks.com/mobile/index.php");
                String logintext = "username=" + TxtUsrname.Text + "&pass=" + TxtPasswd.Password + "&button.x=0&button.y=0";
                loginreq.ContentLength = logintext.Length;
                StreamWriter writerequest = new StreamWriter(loginreq.GetRequestStream());
                writerequest.Write(logintext);
                writerequest.Close();
                HttpWebResponse getloginpageresponse = (HttpWebResponse)loginreq.GetResponse();
                cookie = getloginpageresponse.Cookies[0];
                BinaryFormatter bf1 = new BinaryFormatter();
                Stream f1 = new FileStream("E:\\cookie.dat", FileMode.OpenOrCreate);
                bf1.Serialize(f1, cookie);
                f1.Close();

                string nexturl = getloginpageresponse.Headers[HttpResponseHeader.Location];
                StreamReader readresponse = new StreamReader(getloginpageresponse.GetResponseStream());
                if (nexturl == "p_mprofile.php")
                {
                    MessageBox.Show("Login Successful");
                    GrpMsg.IsEnabled = true;
                }
                else if (nexturl == "index.php?msg=1")
                {
                    MessageBox.Show("Invalid Credentials Login again");
                }

これは私のcreatereqクラスです。

 private HttpWebRequest createreq(string url)
        {
            HttpWebRequest temp = (HttpWebRequest)WebRequest.Create(url);
            temp.Method = "POST";
            temp.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; .NET CLR 3.5.21022; FDM)";
            temp.KeepAlive = true;
            temp.ContentType = "application/x-www-form-urlencoded";
            temp.CookieContainer = new CookieContainer();
            temp.AllowAutoRedirect = false;
            return temp;
        }

私は正しい軌道に乗っていますか?それを行うための任意のより良い方法はありますか?

役に立ちましたか?

解決

あなたは System.Net.WebClientを使用する必要があります。

あなたが好きで、簡単なストリームの読み取りと結果のページを取得したい任意の方法およびヘッダーを含む要求を行うためにそれを使用することができます。

MSDNページ上の簡単な例ではありますが、それを使用するためのいくつかのサンプルコードは、次のようになります。

WebClient webclient= new WebClient();

using (StreamReader reader = new StreamReader(webclient.OpenRead("http://www.google.com")))
{
        string result = reader.ReadToEnd();
         // Parse web page here
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top