HttpWebRequest仅在使用POST模式时获取404页面

本文关键字:模式 获取 404页面 POST HttpWebRequest | 更新日期: 2023-09-27 17:57:35

首先:我知道这个问题已经被问了100多次,但这些问题大多是由超时问题、Url不正确或提前关闭流引起的(相信我,我尝试了所有的示例,但都不起作用)。所以,现在我的问题是:在我的WindowsPhone应用程序中,我使用HttpWebRequest将一些数据POST到phpWeb服务。然后,该服务应该将数据保存在一些目录中,但为了简化它,目前它只回复"hello"。但是,当我使用以下代码时,我总是得到一个404,其中包含一个apache404html文档。因此,我想我可以排除暂停的可能性。请求似乎到达了服务器,但由于某种原因,返回了404。但真正让我惊讶的是,如果我使用get请求,一切都很好。这是我的代码:

HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(server + "getfeaturedpicture.php?randomparameter="+ Environment.TickCount);
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.Method = "POST";
webRequest.ContentType = "text/plain; charset=utf-8";
StreamWriter writer = new StreamWriter(await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null));
writer.Write(Encoding.UTF8.GetBytes("filter=" + Uri.EscapeDataString(filterML)));
writer.Close();
webRequest.BeginGetResponse(new AsyncCallback((res) =>
{
    string strg = getResponseString(res);
    Stator.mainPage.Dispatcher.BeginInvoke(() => { MessageBox.Show(strg); });
}), webRequest);

虽然我不认为这是原因,但以下是getResponseString:的来源

public static string getResponseString(IAsyncResult asyncResult)
{
    HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse webResponse;
    try
    {
        webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
    }
    catch (WebException ex)
    {
        webResponse = ex.Response as HttpWebResponse;
    }
    MemoryStream tempStream = new MemoryStream();
    webResponse.GetResponseStream().CopyTo(tempStream);
    tempStream.Position = 0;
    webResponse.Close();
    return new StreamReader(tempStream).ReadToEnd();
}

HttpWebRequest仅在使用POST模式时获取404页面

这是经过测试的代码,在Post方法中可以很好地使用一些body。愿这能给你一个主意。

public  void testSend()
  {
      try
      {
          string url = "abc.com";
          string str = "test";
          HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
          req.Method = "POST";
          req.ContentType = "text/plain; charset=utf-8";
          req.BeginGetRequestStream(SendRequest, req);
      }
      catch (WebException)
      {
      }
}
//Get Response and write body
 private void SendRequest(IAsyncResult asyncResult)
        {
          string str = "test";
          string Data = "data=" + str;
          HttpWebRequest req= (HttpWebRequest)asyncResult.AsyncState;
          byte[] postBytes = Encoding.UTF8.GetBytes(Data);
          req.ContentType = "application/x-www-form-urlencoded";
          req.ContentLength = postBytes.Length;
          Stream requestStream = req.GetRequestStream();
          requestStream.Write(postBytes, 0, postBytes.Length);
          requestStream.Close();
          request.BeginGetResponse(SendResponse, req);
        }
//Get Response string
 private void SendResponse(IAsyncResult asyncResult)
        {
            try
            {
                MemoryStream ms;
                HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                string _responestring = string.Empty;
                using (Stream data = response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    _responestring = reader.ReadToEnd();
                 }
              }
       catch (WebException)
      {
      }
   }

我建议您在windows phone中使用RestSharp处理POST请求。我正在为一家初创公司制作一款应用程序,在使用与你类似的代码时遇到了很多问题。这是一个使用RestSharp发布请求的例子。你看,不使用3个函数,它可以以更简洁的形式完成。而且可以有效地处理响应。你可以从Nuget获得RestSharp。

RestRequest request = new RestRequest("your url", Method.POST);
            request.AddParameter("key", value);
            RestClient restClient = new RestClient();
            restClient.ExecuteAsync(request, (response) =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    StoryBoard2.Begin();
                    string result = response.Content;
                    if (result.Equals("success"))
                        message.Text = "Review submitted successfully!";
                    else
                        message.Text = "Review could not be submitted.";
                    indicator.IsRunning = false;
                }
                else
                {
                    StoryBoard2.Begin();
                    message.Text = "Review could not be submitted.";
                }
            });

原来问题出在服务器端:它在一个朋友的服务器上尝试了一下,结果很好。我会联系旅馆的支持人员,并在收到回复后尽快提供详细信息。