HTTP POST请求问题

时间:2012-06-22 16:43:10

标签: c# .net http post client-server

我正在使用HttpWebRequest向PHP服务器发送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服务应用程序的计算机使用Wifi连接到Internet。连接有时真的很差。这会引起提到的问题吗?如何使HTTP POST请求对此行为安全。

1 个答案:

答案 0 :(得分:1)

我没有看到任何&#34;定制&#34;你使用的行为,为什么不使用WebClient.UploadData方法呢?然后你会知道这不是你做错了什么

它完成所有&#34;脏&#34;为你工作,你也可以添加内容类型标题。

查看该链接以获取更多信息: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;
}