Is WebClient really unavailable to .NET 3.5 CF?

廉价感情. 提交于 2019-12-02 08:58:47

WebClient doesn't exist, though really it's really not all that important to have. You can get by with a HttpWebRequest for most any of what you'll be doing.

Something along these lines (from the OpenNETCF Extensions):

private string SendData(string method, string directory, string data, string contentType, int timeout)
{
    lock (m_syncRoot)
    {
        directory = directory.Replace('\\', '/');
        if (!directory.StartsWith("/"))
        {
            directory = "/" + directory;
        }

        string page = string.Format("{0}{1}", DeviceAddress, directory);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(page);
#if !WINDOWS_PHONE
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;
#endif
        request.Method = method;

        // turn our request string into a byte stream
        byte[] postBytes;

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

#if !WINDOWS_PHONE
        if (timeout < 0)
        {
            request.ReadWriteTimeout = timeout;
            request.Timeout = timeout;
        }

        request.ContentLength = postBytes.Length;
        request.KeepAlive = false;
#endif
        if (contentType.IsNullOrEmpty())
        {
            request.ContentType = "application/x-www-form-urlencoded";
        }
        else
        {
            request.ContentType = contentType;
        }

        try
        {
            Stream requestStream = request.GetRequestStream();

            // now send it
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();


            using (var response = (HttpWebResponse)request.GetResponse())
            {
                return GetResponseString(response);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            request.Abort();
            return string.Empty;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!