1

私の状況を考慮してください:

HTTP POSTリクエストを学校のサーバーの1つに送信して情報を取得するWindows Phone 7アプリケーションを開発しています。Web サイトにアクセスすると、認証コードの画像が表示されます。学校番号、パスワード、および認証コードを入力してログインする必要があります。その後、必要なものにアクセスできます。

私は、サーバーがクライアントクッキーを書き込んで、あなたがログインしていることを確認することを確認しました。ログイン処理を実装したい場合は、getVerifyCode() メソッドの uploadStringCompleted メソッドにコードを記述する必要があります。ベストプラクティスではないと思います。例えば:

(注: これは単なる例であり、実際のコードではありません。検証コードを取得するには、GET メソッドの HTTP 要求が必要なだけなので、問題を説明できると思います)

public void getVerifyCode()
{
    webClient.uploadStringCompleted += new uploadStringCompleted(getVerifyCodeCompleted);
    webClient.uploadStringAsync(balabala, balabala, balabala);
}

private void getVerifyCodeCompleted(object sender, uploadStringCompletedArgs e)
{
    if(e.Error == null)
    {
        webClient.uploadStringCompleted -= getVerifyCodeCompleted;

        // start log in 
        // I don't submit a new request inside last request's completed event handler
        // but I can't find a more elegent way to do this.
        webClient.uploadStringCompleted += loginCompleted;
        webClient.uploadStringAsync(balabala, balabala, balabala);
    }
}

一言で言えば、上記のような問題を解決するためのベストプラクティスまたはデザインパターンは何ですか?

よろしくお願いします。

4

1 に答える 1

0

HttpWebRequest.BeginGetRequestStream / EndRequestStream を使用したコード スニペットを次に示します。

HttpWebRequest webRequest = WebRequest.Create(@"https://www.somedomain.com/etc") as HttpWebRequest;
webRequest.ContentType = @"application/x-www-form-urlencoded";
webRequest.Method = "POST";

// Prepare the post data into a byte array
string formValues = string.Format(@"login={0}&password={1}", "someLogin", "somePassword");
byte[] byteArray = Encoding.UTF8.GetBytes(formValues);

// Set the "content-length" header 
webRequest.Headers["Content-Length"] = byteArray.Length.ToString();

// Write POST data
IAsyncResult ar = webRequest.BeginGetRequestStream((ac) => { }, null);
using (Stream requestStream = webRequest.EndGetRequestStream(ar) as Stream)
{
    requestStream.Write(byteArray, 0, byteArray.Length);
    requestStream.Close();
}

// Retrieve the response
string responseContent;    

ar = webRequest.BeginGetResponse((ac) => { }, null);
WebResponse webResponse = webRequest.EndGetResponse(ar) as HttpWebResponse;
try
{
    // do something with the response ...
    using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
    {
        responseContent = sr.ReadToEnd();
        sr.Close();
    }
}
finally
{
    webResponse.Close();
}

UI/メインスレッドの応答性を維持するために、ThreadPool.QueueUserWorkItem で実行する必要があることに注意してください。

于 2013-02-22T23:46:59.420 に答える