[英]HttpWebRequest get 404 page only when using POST mode
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). 首先:我知道这已被问过100多次了,但是大多数问题都是由于超时问题,错误的Url或者预先关闭流而引起的(并且相信我,我尝试了所有的样本而没有一个问题)工作)。 So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service.
所以,现在我的问题是:在我的Windows Phone应用程序中,我正在使用HttpWebRequest将一些数据发送到php Web服务。 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.
但是当我使用下面的代码时,我总是得到404完整的apache 404 html文档。 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.
似乎请求到达服务器,但由于某种原因,返回404。 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: 虽然我不认为这是原因,但这里是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();
}
This is tested code work fine in Post method with some body. 这是经过测试的代码在Post方法中运行得很好。 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. 我建议你在Windows Phone中使用RestSharp来处理你的POST请求。 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.
下面是使用RestSharp发布请求的示例。 You see, instead of using 3 functions it can be done in a more concise form.
您可以看到,它可以以更简洁的形式完成,而不是使用3个函数。 Also the response can be handled efficiently.
此外,响应可以有效地处理。 You can get RestSharp from Nuget .
你可以从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.";
}
});
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.
我会在收到回复后立即联系主办方的支持并提供详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.