2012-06-22 190 views
0

我使用HttpWebRequest向PHP服務器發送HTTP POST請求。 我的代碼是這樣的:HTTP POST請求問題

/// <summary> 
    /// Create Post request. 
    /// </summary> 
    /// <param name="requestUrl">Requested url.</param> 
    /// <param name="postData">Post data.</param> 
    /// <exception cref="RestClientException">RestClientException</exception> 
    /// <returns>Response message, can be null.</returns> 
    public string Post(string requestUrl, string postData) 
    { 
     try 
     { 
      //postData ends with & 
      postData = "username=XXX&password=YYYY&" + postData; 

      byte[] data = UTF8Encoding.UTF8.GetBytes(postData); 

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); 
      request.Method = RequestMethod.Post.ToString().ToUpper(); 
      request.ContentType = "application/x-www-form-urlencoded"; 
      request.ContentLength = data.Length; 

      using (Stream stream = request.GetRequestStream()) 
      { 
       stream.Write(data, 0, data.Length); 
       stream.Flush(); 
      } 

      string responseString; 
      using (WebResponse response = request.GetResponse()) 
      { 
       responseString = GetResponseString(response); 
      } 

      return responseString; 
     } 
     catch (WebException ex) 
     { 
      var httpResponse = (HttpWebResponse)ex.Response; 
      if (httpResponse != null) 
      { 
       throw new RestClientException(GetExceptionMessage(httpResponse)); 
      } 

      throw; 
     } 
    } 

我遇到奇怪的行爲。我每分鐘都會發送100個請求。但有時候,這個請求會隨着POST數據執行。然後我的PHP服務器返回錯誤(因爲我正在檢查請求是否爲POST,以及它是否有任何POST數據)。

這是一個客戶端/服務器通信。帶有Windows Service應用程序的計算機通過Wifi連接到互聯網。連接有時真的很差。這可能導致問題提及嗎?如何使HTTP POST請求安全地抵禦這種行爲。

+2

你確定它是沒有POST數據_your_請求?它可能是其他人掃描服務器的漏洞,發送其他類型的隨機請求。 –

+0

你確定你總是提供數據(即你的'postData'可能是空的/錯的)? –

+0

請參閱「[堆棧溢出不允許標題在標題中](http://meta.stackexchange.com/a/130208)」 –

回答

1

我沒有看到您使用的任何「自定義」行爲,那麼您爲什麼不使用WebClient.UploadData方法?那麼你會知道這不是你正在做的錯誤

它爲你做所有的「髒」工作,你也可以添加內容類型頭。

看看這個鏈接獲取更多信息:http://msdn.microsoft.com/en-us/library/tdbbwh0a(v=vs.80).aspx

例如:

public string Post(string requestUrl, string postData) 
{ 
    WebClient myWebClient = new WebClient(); 
    myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded"); 
    byte[] data = UTF8Encoding.UTF8.GetBytes(postData); 
    byte[] responseArray = myWebClient.UploadData(requestUrl,data); 
    return responseArray; 
} 
+0

謝謝。我真的不知道爲什麼我選擇了不同的方法。我將嘗試使用WebClient類。 – Simon