HttpWebRequest失败紧凑框架

时间:2016-02-18 10:56:30

标签: c# .net compact-framework http-request

尝试在Windows Mobile 6.5设备上发出Http POST请求

我可以在设备上的浏览器中查看网页,但Http请求失败

private string SendData(string directory, string data)
    {
        string page = string.Format("http://{0}/{1}", hostname, directory);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(page);
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "POST";
        request.ContentType = "text/json";

        byte[] postBytes;

        if (data != null)
        {
            postBytes = Encoding.UTF8.GetBytes(data);
        }
        else
        {
            postBytes = new byte[0];
        }

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postBytes.Length;

        /*
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();
        */
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
                Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
                                     response.StatusDescription);
        }
        catch (WebException e) {
            Debug.WriteLine("\r\nWebException Raised. The following error occured : "+e.Status);
        }

    }

我现在已经注释掉了POST流,直到我可以获得一个简单的请求

没有try catch我得到“无法连接到远程服务器”并崩溃。

1 个答案:

答案 0 :(得分:2)

原来这个代码很好

当通过USB插入计算机时,设备会断开连接 关闭Windows Mobile设备中心后,它运行正常。