2012-06-11 30 views
0

一個朋友告訴我這個示例代碼,C#實現HTTP POST,做的winform應用程序計算出: http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/爲什麼我收到此錯誤:遠程服務器返回錯誤:(417)預期失敗

而在Metro應用中實現:

// this is what we are sending 
string post_data = "[email protected]&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. 

我想最後一個屬性是解決方案。我怎麼解決這個問題? 在此先感謝

+0

嘗試在頂部放置以下代碼:'ServicePointManager.Expect100Continue = false;'另外,爲什麼使用Async版本的方法,然後使用'await'進行阻塞,所有這些函數都有同步版本。 –

回答

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", "[email protected]"), 
           new HttpPostParam("pass", "example123") 
          }; 
string response = PostTrivialData(new Uri("http://app.proceso.com.mx/win8/login"), httpparams); 

讓我知道,如果有任何問題。

相關問題