.net 从WindowsMobile6.5Compact框架调用RESTfulWebService
我正在尝试从windows mobile 6.5 compact framework客户端调用服务。这会导致异常“无法从传输连接读取数据” 我使用的模拟器是Windows mobile 6 professional emulator。dotnetframework3。仿真器连接到internet。我可以从互联网上打开网页。如果创建一个C#Windows控制台应用程序,同样的代码运行良好。请导游.net 从WindowsMobile6.5Compact框架调用RESTfulWebService,.net,web-services,rest,windows-mobile,compact-framework,.net,Web Services,Rest,Windows Mobile,Compact Framework,我正在尝试从windows mobile 6.5 compact framework客户端调用服务。这会导致异常“无法从传输连接读取数据” 我使用的模拟器是Windows mobile 6 professional emulator。dotnetframework3。仿真器连接到internet。我可以从互联网上打开网页。如果创建一个C#Windows控制台应用程序,同样的代码运行良好。请导游 WebRequest Webrequest; HttpWebRespo
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();
我不知道你的代码到底出了什么问题。在发出web请求之前,可能必须设置一些属性。下面是我用来从web服务获取时区信息的一个片段:
/// <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
}
}
//
///这将异步调用webservice
///电话将立即返回
///请求的答案将发布到所有事件订阅者
///
///地理纬度的十进制输入
///地理经度的十进制输入
公共无效startRequest(字符串lat、字符串lng)
{
//tzInfos pTZinfos=新的tzInfos();
字符串myURL=@“http://ws.geonames.org/“+_webMethodName;
//HttpWebRequest webRequest=(HttpWebRequest)HttpWebRequest.Create(myURL);
//HttpWebResponse webResponse=(HttpWebResponse)webRequest.GetResponse();
//字符串wsdl=“”;
_webServiceURI=myURL;
尝试
{
_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;
//异步调用
IAsyncResult MyAsycnCCall=this.\u httpRequest.BeginGetResponse(新的AsyncCallback(this.ResponseReceivedHandler)),null;
}
捕获(WebException wx)
{
System.Diagnostics.Debug.WriteLine(“异常:+wx.Message”);
}
捕获(异常wx)
{
System.Diagnostics.Debug.WriteLine(“异常:+wx.Message”);
}
}
///
///这是从web服务获取响应的异步方法
///
///
私有void ResponseReceivedHandler(IAsyncResult结果)
{
字符串wsdl=“”;
geonamesTZfields pTZinfos=新的geonamesTZfields();
geonamesEventArgs target=新的geonamesEventArgs();
尝试
{
HttpWebResponse=(HttpWebResponse)this.\u httpRequest.EndGetResponse(结果);
System.IO.streamResponse=response.GetResponseStream();
System.IO.StreamReader streamRead=新的System.IO.StreamReader(streamResponse);
wsdl=streamRead.ReadToEnd();
System.Diagnostics.Debug.WriteLine(“响应:+wsdl”);
//关闭流对象
streamResponse.Close();
streamRead.Close();
//发布HttpWebResponse
response.Close();
如果(wsdl.Length>0)
{
StringBuilder sb=新的StringBuilder(wsdl);
pTZinfos.strCountryCode=xml_helper.xml_helper.getstrset(sb,“国家代码”);
pTZinfos.strCountryName=xml_helper.xml_helper.getStrSetting(sb,“countryName”);
pTZinfos.strTimezoneID=xml_helper.xml_helper.getstrset(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,“时间”);
}
_tzFields=pTZinfos;
//解雇事件
target.m_myEventArgumentdata=pTZinfos;
target.m_myEventArgumentdata.DataIsValid=true;
target.m_myEventArgumentdata.strLastError=“无错误”;
}
捕获(WebException wx)
{
target.m_myEventArgumentdata.DataIsValid=false;
target.m_myEventArgumentdata.strLastError=wx.Message;
}
捕获(例外情况除外)
{
target.m_myEventArgumentdata.DataIsValid=false;
target.m_myEventArgumentdata.strLastError=例如消息;
}
最后
{
this.onDataReceived(target);//通知所有订阅服务器新数据已到达
}
}
你看,我明确地设置了一些属性:
_httpRequest.Method=“POST”;
_httpRequest.KeepAlive=false;
_httpRequest.ContentType=“application/x-www-form-urlencoded”;
//httpRequest.ContentLength=requestData.Length;
_httpRequest.Timeout=30000;
完整代码可在我的文章中找到:。您可以使用它,更改web请求并使用异步调用
您也可以尝试在设备上的Internet Explorer Mobile中简单地打开网页。您应将答案回复为:
{“postalCodes”:[{“adminCode3”:“3203”,“adminName2”:“Wahlkreis St.Gallen”,“adminName3”:“St.Gallen”,“adminCode2”:“1721”,“adminCode1”:“SG”,“postalCode”:“9011”,“countryCode”:“CH”,“lng”:9.399845287638328,“地名”:“St.Gallen”,“lat”:47.414775553450646,“adminName1”:“Kanton St.Gallen”},“adminCode1”:“GS”,“postalCode”:“9011”,“countryCode”:“HU”,“lng”:17.781944437499998,“地名”:“Győr”,“lat”:47.60763890000005,“adminName1”:“Győr-Moson-Sopron”},{“adminName2”:“Tromsø”,“adminCode2”:“1902”,“adminCode1”:“19”,“postalCode”:“9011”,“countryCode”:“NO”,“lng”:18.95508,“地名”:“Tromsø”,“ISO3166-2”:“10”,“lat”:69.6489,“adminName1”:“Troms”},“postalCode”:“L-9011”,“countryCode”,“地名”:“Ettelbruck”,“lat”:49.8475},{“adminCode1”:“Z”,“postalCode”:”
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);
}
}
}