Search code examples
c#.netcompact-frameworkhttp-request

HttpWebRequest Fails Compact Framework


Trying to make a Http POST request on a windows mobile 6.5 device

I can view the web page in a browser on the device but the Http request fails

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

    }

I have commented out the POST Stream for now until I can get a simple request working

Without the try catch I get "Unable to connect to remote server" and crashes.


Solution

  • Turns out this code is fine

    When plugged into a computer via USB, the device lost its connections.
    After closing the Windows Mobile Device Center, it worked fine.