Pergunta

First of all: I know this has been asked over 100 times, but most of these questions were eigher caused by timeout problems, by incorrect Url or by foregetting to close a stream (and belive me, I tried ALL the samples and none of them worked). So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service. That service should then save the data in some directories, but to simplify it, at the moment, it only echos "hello". But when I use the following code, I always get a 404 complete with an apache 404 html document. Therefor I think I can exclude the possibility of a timeout. It seems like the request reaches the server, but for some reason, a 404 is returned. But what really makes me be surprised is, if I use a get request, everything works fine. So here is my code:

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);

Although I don't think this is the reason, here's the source of 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();
}
Foi útil?

Solução 3

It turned out the problem was on the server-side: it tried it on the server of a friend and it worked fine, there. I'll contact the support of the hoster and provide details as soon as I get a response.

Outras dicas

This is tested code work fine in Post method with some body. May this gives you an idea.

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)
      {

      }
   }

I would suggest you to use RestSharp for your POST requests in windows phone. I am making an app for a startup and i faced lots of problems while using a similar code as yours. heres an example of a post request using RestSharp. You see, instead of using 3 functions it can be done in a more concise form. Also the response can be handled efficiently. You can get RestSharp from Nuget.

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.";
                }
            });
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top