0

友人が C# で HTTP POST を実装するこのサンプル コードを見せてくれ、 WINFORMアプリでうまくいきました 。 request-with-c/

そしてMETRO APPに実装されています:

 // this is what we are sending
string post_data = "user=user@example.com&pass=example123";

// this is where we will send it
string uri = "http://app.proceso.com.mx/win8/login";

// create a request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";

// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(post_data);

// this is important - make sure you specify type this way
request.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = await request.GetRequestStreamAsync();

// now send it
requestStream.Write(postBytes, 0, postBytes.Length);

// grab te response and print it out to the console along with the status code
WebResponse response = await request.GetResponseAsync();
//var a = new StreamReader(response.GetResponseStream()).ReadToEnd();
StreamReader requestReader = new StreamReader(response.GetResponseStream());
String webResponse = requestReader.ReadToEnd();

HttpWebRequest には ProtocolVersion が含まれておらず、次の行にこのエラーがスローされていることに気付きました。

WebResponse response = await request.GetResponseAsync();
// ERROR: The remote server returned an error: (417) Expectation Failed.

最後のプロパティが解決策だと思います。どうすればこの問題を解決できますか? 前もって感謝します

4

1 に答える 1

1

私は最近、サーバーへの些細なデータの投稿を処理する小さな関数を作成しました。

private struct HttpPostParam
{
    private string _key;
    private string _value;

    public string Key { get { return HttpUtility.UrlEncode(this._key); } set { this._key = value; } }
    public string Value { get { return HttpUtility.UrlEncode(this._value); } set { this._value = value; } }

    public HttpPostParam(string key, string value)
    {
        this._key = key;
        this._value = value;
    }
};

private static string PostTrivialData(Uri page, HttpPostParam[] parameters)
{
    string pageResponse = string.Empty;
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(page); //create the initial request.
        request.Method = WebRequestMethods.Http.Post; //set the method
        request.AllowAutoRedirect = true; //couple of settings I personally prefer.
        request.KeepAlive = true;
        request.ContentType = "application/x-www-form-urlencoded";

        //create the post data.
        byte[] bData = Encoding.UTF8.GetBytes(string.Join("&", Array.ConvertAll(parameters, kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))));
        using (var reqStream = request.GetRequestStream())
            reqStream.Write(bData, 0, bData.Length); //write the data to the request.

        using (var response = (HttpWebResponse)request.GetResponse()) //attempt to get the response.
            if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NotModified) //check for a valid status (should only return 200 if successful)
                using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
                    pageResponse = reader.ReadToEnd();
    }
    catch (Exception e)
    {
        /* todo: any error handling, for my use case failing gracefully was all that was needed. */
    }
    return pageResponse;
}

基本的に、「パラメーター」引数で定義された値のペアを投稿します。コンパイルするには、System.Web 名前空間の参照とインポートが必要です。

あなたのウェブサイトでテストしたところ、応答が返ってきました。

HttpPostParam[] httpparams = {
                                new HttpPostParam("user", "censored@email.com"),
                                new HttpPostParam("pass", "example123")
                             };
string response = PostTrivialData(new Uri("http://app.proceso.com.mx/win8/login"), httpparams);

問題があればお知らせください。

于 2012-06-11T04:45:57.850 に答える