【发布时间】:2011-07-06 00:15:37
【问题描述】:
我正在尝试从我的 Windows Phone 7 应用程序对 Web 服务执行非常基本的 http POST。我知道 Web 服务运行良好,因为我将它用于其他三个移动平台。
我已经修改了 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx 中的 C# 示例
string boundary = DateTime.Now.Ticks.ToString();
private void POST_TEST(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constants.JSON_URL_PREFIX + Settings.Settings.DeviceID + "/inquiry/new/");
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
StringBuilder postData = new StringBuilder();
postData.Append("--" + boundary + "\r\n");
postData.Append("Content-Disposition: form-data; name=\"body\"\r\n\r\n");
postData.Append("test 123");
postData.Append("\r\n--" + boundary + "\r\n");
byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
当我在模拟器中运行它时,我从服务器收到“{ result: 'ok' }”,但是当我在三星 Focus 上运行它时收到“错误:NotFound”。我假设这与在手机上将字符串转换为 byte[] 与在台式计算机上的方式有关。
关于修复的任何想法?也许这是我在网上搜索答案时从未遇到过的已知错误?
【问题讨论】:
-
请求是否到达服务器?你能从设备上的 IE 连接到服务器吗?
-
是的,请求到达服务器。我知道这一点是因为我收到了来自服务器的响应。这不仅仅是超时。是的,我可以在设备上连接到 IE 中的 Web 服务。
-
如果您的设备(通过 IE)无法连接到服务器,那么这应该是您的首要调查点。如果无法从设备连接到服务器,则更改代码将无济于事。
标签: http windows-phone-7 post httpwebrequest