【问题标题】:Invoke restful webservice from windows mobile 6.5 compact framework从 windows mobile 6.5 compact framework 调用 restful webservice
【发布时间】:2013-11-05 01:21:03
【问题描述】:

我正在尝试从 windows mobile 6.5 compact 框架客户端调用服务。这给了我异常“无法从传输连接读取数据”。

我使用的模拟器是 Windows mobile 6 专业模拟器。 Dotnet 框架 3. 模拟器连接到互联网。我可以从互联网打开网页。如果创建 C# Windows 控制台应用程序,相同的代码运行良好。请指导。

        WebRequest Webrequest;
        HttpWebResponse response=null;

        Webrequest = WebRequest.Create("http://api.geonames.org/postalCodeSearchJSON?postalcode=9011&maxRows=10&username=demo");

        Webrequest.Method = "GET";
        Webrequest.ContentType = "html/xml";
        try
        {
            response = (HttpWebResponse)Webrequest.GetResponse();
        }catch(Exception exc){
            ShowErrorMessage("Ex : " + exc.Message);

            return;
        }

        Stream streamResponse = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(streamResponse);
        string responseStr = streamReader.ReadToEnd();

【问题讨论】:

    标签: .net web-services rest windows-mobile compact-framework


    【解决方案1】:

    我不知道您的代码到底有什么问题。可能您必须在发出 Web 请求之前设置一些属性。这是我用来从网络服务获取时区信息的 sn-p:

        /// <summary>
        /// This will call the webservice asynchronousely
        /// the call will immediately return
        /// The answer on the request is published to all event subscribers
        /// </summary>
        /// <param name="lat">decimal input for geographic Latitude</param>
        /// <param name="lng">decimal input for geographic Longitude</param>
        public void startRequest(string lat, string lng)
        {
            //tzInfos pTZinfos = new tzInfos();
            string myURL = @"http://ws.geonames.org/" + _webMethodName;
            //HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myURL);
            //HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            //string wsdl = "";
            _webServiceURI = myURL;
            try
            {
                _httpRequest = (HttpWebRequest)HttpWebRequest.Create(this._webServiceURI + "?lat=" + lat + "&lng=" + lng); // "?WSDL");
                _httpRequest.Method = "POST";
                _httpRequest.KeepAlive = false;
                _httpRequest.ContentType = "application/x-www-form-urlencoded";
                //httpRequest.ContentLength = requestData.Length;
                _httpRequest.Timeout = 30000;
    
                //async call
                IAsyncResult myAsycnCall = this._httpRequest.BeginGetResponse(new AsyncCallback(this.ResponseReceivedHandler), null);                
            }
            catch (WebException wx)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + wx.Message);
            }
            catch (Exception wx)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + wx.Message);
            }
        }
        /// <summary>
        /// This is the async method for the response to be get from the web service
        /// </summary>
        /// <param name="result"></param>
        private void ResponseReceivedHandler(IAsyncResult result)
        {
            string wsdl = "";
            geonamesTZfields pTZinfos = new geonamesTZfields();
            geonamesEventArgs tArg = new geonamesEventArgs();
            try
            {
                HttpWebResponse response = (HttpWebResponse)this._httpRequest.EndGetResponse(result);
    
                System.IO.Stream streamResponse = response.GetResponseStream();
                System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse);
                wsdl = streamRead.ReadToEnd();
                System.Diagnostics.Debug.WriteLine("Response: " + wsdl);
    
                // Close the stream object
                streamResponse.Close();
                streamRead.Close();
    
                // Release the HttpWebResponse
                response.Close();
                if (wsdl.Length > 0)
                {
                    StringBuilder sb = new StringBuilder(wsdl);
                    pTZinfos.strCountryCode = xml_helper.xml_helper.getStrSetting(sb, "countryCode");
                    pTZinfos.strCountryName = xml_helper.xml_helper.getStrSetting(sb, "countryName");
                    pTZinfos.strTimezoneID = xml_helper.xml_helper.getStrSetting(sb, "timezoneId");
                    pTZinfos.gmtOffset = xml_helper.xml_helper.getDecimalSetting(sb, "gmtOffset");
                    pTZinfos.rawOffset = xml_helper.xml_helper.getDecimalSetting(sb, "rawOffset");
                    pTZinfos.dstOffset = xml_helper.xml_helper.getDecimalSetting(sb, "dstOffset");
                    pTZinfos.tzTime = xml_helper.xml_helper.getDateTimeSetting(sb, "time");
                }
                _tzFields = pTZinfos;
                //fire the event
                tArg.m_myEventArgumentdata = pTZinfos;
                tArg.m_myEventArgumentdata.DataIsValid = true;
                tArg.m_myEventArgumentdata.strLastError = "no error";
            }
            catch (WebException wx)
            {
                tArg.m_myEventArgumentdata.DataIsValid = false;
                tArg.m_myEventArgumentdata.strLastError = wx.Message;
            }
            catch (Exception ex)
            {
                tArg.m_myEventArgumentdata.DataIsValid = false;
                tArg.m_myEventArgumentdata.strLastError = ex.Message;
            }
            finally
            {
                this.onDataReceived(tArg); //notify all subscribers of new data arrived
            }
        }
    

    你看我明确设置了一些属性: _httpRequest.Method = "POST"; _httpRequest.KeepAlive = false; _httpRequest.ContentType = "应用程序/x-www-form-urlencoded"; //httpRequest.ContentLength = requestData.Length; _httpRequest.Timeout = 30000; 完整代码可在我的文章中找到:http://www.hjgode.de/wp/2010/03/04/using-ws-geonames-org-timezone-webservice-without-wsdl/。您可以使用它并更改您的网络请求并使用异步调用。

    您也可以尝试在设备上的 Internet Explorer Mobile 中简单地打开网页:http://api.geonames.org/postalCodeSearchJSON?postalcode=9011&maxRows=10&username=demo。你应该得到答案:

    {"postalCodes":[{"adminCode3":"3203","adminName2":"Wahlkreis St. Gallen","adminName3":"St. Gallen","adminCode2":"1721","adminCode1" :"SG","postalCode":"9011","countryCode":"CH","lng":9.399845287638328,"placeName":"St. Gallen","lat":47.414775553450646,"adminName1":"Kanton St .加仑"},{"adminCode1":"GS","postalCode":"9011","countryCode":"HU","lng":17.781944437499998,"placeName":"Győr","lat":47.607638900000005, "adminName1":"Győr-Moson-Sopron"},{"adminName2":"Tromsø","adminCode2":"1902","adminCode1":"19","postalCode":"9011","countryCode": "NO","lng":18.95508,"placeName":"Tromsø","ISO3166-2":"10","lat":69.6489,"adminName1":"Troms"},{"postalCode":"L -9011","countryCode":"LU","lng":6.1041667,"placeName":"Ettelbruck","lat":49.8475},{"adminCode1":"Z","postalCode":"9011", "countryCode":"AR","lng":-67.5333333,"placeName":"CALETA OLIVIA","lat":-46.4333333,"adminName1":"SANTA CRUZ"},{"adminCode1":"Z", "postalCode":"9011","countryCode":"AR","lng":-67.5333333,"placeName":"EL MANGRULLO","lat":-46.43333 33,"adminName1":"SANTA CRUZ"},{"adminCode1":"Z","postalCode":"9011","countryCode":"AR","lng":-67.5333333,"placeName":"CAÑADON ESTHER","lat":-46.4333333,"adminName1":"SANTA CRUZ"},{"adminCode1":"Z","postalCode":"9011","countryCode":"AR","lng":- 67.5333333,"placeName":"BAHIA LANGARA","lat":-46.4333333,"adminName1":"SANTA CRUZ"},{"postalCode":"9011","countryCode":"NZ","lng":170.47198 ,"placeName":"Mornington","lat":-45.87922},{"postalCode":"9011","countryCode":"PH","lng":124.7325,"placeName":"八岭关","lat ":9.050317457142857}]}

    如果 Internet Explorer Mobile 中没有,则您的连接设置不正确查找 WMDC 连接设置和“此计算机连接到”。从 Internet 切换到自动可能会有所帮助。我假设您已对接您使用的模拟器,并且 WMDC 或 ActiveSync 显示与模拟器的连接。

    【讨论】:

    • 我也无法在 Internet Explorer 中打开此特定链接。但是,我可以从模拟器连接到 Internet。我可以在我的模拟器上打开 stackoverflow。我在谷歌搜索异常“无法从传输连接读取数据”,他们说这与手机的 MTU 和一些我无法理解的注册表编辑有关。 social.msdn.microsoft.com/Forums/en-US/…
    • 如果注册表更改解决了您的问题,请尝试一下:您可以使用远程注册表编辑器(如 MS sdk 或 CeRegEditor 随附的:ceregeditor.mdsoft.pl)。然后查找 HKEY_LOCAL_MACHINE\Comm\Tcpip\Parms 并将 MTU 的值设置为 1300 字节(514 为十六进制)并添加一个 DOWRD 值 EnablePMTUDiscovery 并将值设置为 0。您上面提供的链接还包含一些 .NET 代码来更改reg 值按代码。
    • 感谢您的信息。该问题现在已解决,无需任何更改.. 无需更改注册表,也无需更改代码。我不知道它为什么现在可以工作...如果您对此有所了解,请查看我的另一个问题并留下您的回复。
    【解决方案2】:
    class ServiceConnection
    {
        public string Url = "";
    
        private string postXml;
    
        public delegate void OnServerEndResponse(string response, int statusCode);
        public event OnServerEndResponse OnEndResponse;
        public ServiceConnection(string serviceName, string userName, string pwd)
    
    
        public void SendRequest(string requestXml)
        {
            postXml = requestXml;
            StartWebService();
        }
    
        public void StartWebService()
        {
            WebRequest request = WebRequest.Create(Url);
            request.Method = "GET";
            byte[] auth = Encoding.UTF8.GetBytes(UserName + ":" + Pwd);
            request.Headers["Authorization"] = "Basic " + System.Convert.ToBase64String(auth);
            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
        }
    
        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebResponse response = null;
            HttpWebRequest webRequest = null;
    
            try
            {
                webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(streamResponse);
                StringBuilder sb = new StringBuilder();
                sb.Append(streamReader.ReadToEnd());
                //string serverResponse = streamReader.ReadToEnd();
                streamResponse.Close();
                streamReader.Close();
                response.Close();
    
    
                OnEndResponse(sb.ToString(), Convert.ToInt32(response.StatusCode));
            }
            catch (Exception ex)
            {
                if (ex.Message == "The remote server returned an error: (401) Unauthorized.")
                    OnEndResponse(ex.Message, 401);
                else if (ex.Message == "Unable to connect to the remote server")
                    OnEndResponse(ex.Message, 4);
                else if (ex.Message == "Could not establish connection to network.")
                    OnEndResponse(ex.Message, 10000);
                else
                    OnEndResponse("Error in network", 10001);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-18
      • 2011-07-24
      • 2011-01-26
      • 2012-01-09
      • 2010-12-11
      • 1970-01-01
      • 2011-09-05
      • 2010-09-19
      • 2012-07-29
      相关资源
      最近更新 更多