WP7 HttpWebRequest POST,服务器在模拟器中返回“{result:'ok'} \”,但在设备上返回“error:NotFound”

时间:2011-07-06 00:15:37

标签: http windows-phone-7 post httpwebrequest

我正在尝试从我的Windows Phone 7应用程序对Web服务进行非常基本的http POST。我知道网络服务运行正常,因为我将其用于其他三个移动平台。

我已经从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'}”,但是当我在Samsung Focus上运行时,“error:NotFound”。我假设这与将字符串转换为手机上的字节[]与台式计算机的方式有关。

关于修复的任何想法?也许这是一个已知的错误,我从来没有遇到过搜索网页的答案?

2 个答案:

答案 0 :(得分:2)

我终于发现我的手机的唯一身份证/设备ID中有正斜杠。当我在以下位置构建Web服务Uri时,这会导致问题:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constants.JSON_URL_PREFIX + Settings.Settings.DeviceID + "/inquiry/new/");

Uri模拟器示例:http://www.blah.com/abc_123=/inquiry/new/
Uri设备示例:http://www.blah.com/abc/123=/inquiry/new/

显然,它在模拟器中工作正常,因为模拟器的设备ID中没有正斜杠。基本上,我试图发布的Uri是不正确的。

有点晦涩的错误......

感谢Opena和Matt。你的建议给了我一些尝试,最终帮助我看到问题。

答案 1 :(得分:0)

我在app上使用此解决方案,但我的postData看起来像postData.Append("test=123")。我不使用边界(我认为边界只适用于邮件?)
我的request.ContentType也是request.ContentType = "application/x-www-form-urlencoded";