原文链接:http://www.cnblogs.com/VinC/archive/2011/02/24/1964049.html
本章目的: 用Wcf建立可以上AndroID可以访问的数据服务,数据传输格式采用比较适合于移动互联网传输的Json格式.
服务的开发流程我们按照 服务契约(ServiceContract),服务实现(Service),实体对象模型(Model) 及服务发布的流程来介绍.
由于自己对http请求的链接认识的比较浅,对于有些问题没法做出清楚明了的解释,AndroID访问WCF这篇文章我会贴出来代码,让后说明一下关注的地方,不做深入研究.
一. 服务契约(Contract)[ServiceContract] public interface IAccountJsonService { [OperationContract(name = "GetAccountDataJson")] [WebGet(RequestFormat = Webmessageformat.Json,ResponseFormat = Webmessageformat.Json,UriTemplate = "GetAccountData",BodyStyle = WebMessageBodyStyle.bare)] List<Account> GetAccountData(); [OperationContract(name = "SendMessageJson")] [WebInvoke(Method = "GET",UriTemplate = "SendMessage/{Message}",BodyStyle = WebMessageBodyStyle.bare)] string SendMessage(string Message); }
此契约定义了两个方法,GetAccountData(获取Account数据列表,方法不带参数),SendMessage,获取从客户端传过来的数据,并返回;
1. 这里面注意WebInvoke(SendMessage方法)这个Attribute,Method代表了http的访问方法,我们这是从服务器获取数据,是请求数据, 所以用GET,这个也可以用另外一个Attribute来替代-WebGet(GetAccountData方法);
2. 我们要给客户端返回Json数据,我们只需在WebInvoke or WebGet Attribute中指定ResponseFormat的格式即可,这个从名字命名就可以看出来是制定返回的数据格式的.
3. 要注意UriTemplate属性,这个是指定我们请求时的方法路径,后面给出示例.
二. 服务实现(Service)public class AccountService : IAccountJsonService{ public List<Account> GetAccountData() { return MockAccount.AccountList; } public string SendMessage(string Message) { return " Message:" + Message; }}
此处只是实现了IAccountJsonService接口.
三. 实体对象模型&模拟数据 实体类定义:[DataContract] public class Account { [DataMember] public string name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Address { get; set; } [DataMember] public DateTime Birthday { get; set; } }模拟数据:
public class MockAccount { public static List<Account> AccountList { get { var List = new List<Account>(); List.Add(new Account { name = "Bill Gates",Address = "YouYi East Road",Age = 56,Birthday = DateTime.Now }); List.Add(new Account { name = "Steve Paul Jobs",Address = "YouYi West Road",Age = 57,Birthday = DateTime.Now }); List.Add(new Account { name = "John D. Rockefeller",Address = "YouYi north Road",Age = 65,Birthday = DateTime.Now }); return List; } } }
模拟数据返回一个Account的列表,含有三条模拟数据,Birthday用DateTime.Now可是随时查看数据是不是最新生成的.
四. 服务发布
在这个例子里面,我们的服务采用Console的发布形式,如果采用IIS发布,只要参考WCF的服务配置信息,在IIS环境下配置就OK了.
WCF配置信息
<system.serviceModel> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetUrl="mex" httpGetEnabled="true"/> <serviceDeBUG httpHelpPageEnabled="true" includeExceptionDetailinFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="WebhttpBindingBehavior"> <webhttp/> </behavior> </endpointBehaviors> </behaviors> <services> <service name="Hosting.AccountService"> <endpoint address="xml" binding="webhttpBinding" contract="Hosting.IAccountXmlService" behaviorConfiguration="WebhttpBindingBehavior"/> <!--<endpoint address="Json" binding="webhttpBinding" contract="Hosting.IAccountJsonService" behaviorConfiguration="WebhttpBindingBehavior"/>--> <host> <baseAddresses> <add baseAddress="http://127.0.0.1:82/AccountService"/> </baseAddresses> </host> </service> </services> </system.serviceModel>
控制台进行服务的托管发布
class Program { static voID Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(AccountService))) { host.open(); Console.Writeline("AccountService Address:"); foreach (var endpoint in host.Description.Endpoints) { Console.Writeline(endpoint.Address.ToString()); } Console.Writeline("AccountService Started,Press any key to stop service..."); Console.ReadKey(); host.Close(); } } }
下篇将介绍AndroID如何访问我们编写的服务.
示例代码下载
此部分分为 建立http请求 跟 接受WCF 返回的数据.
一. 建立http请求的方法
protected String getRequest(String url,DefaulthttpClIEnt clIEnt) throws Exception { String result = null; int statusCode = 0; httpGet getmethod = new httpGet(url); Log.d(TAG,"do the getRequest,url=" + url + ""); try { getmethod.setheader("User-Agent",USER_AGENT); // httpParams params = new httpParams(); // 添加用户密码验证信息 // clIEnt.getCredentialsProvIDer().setCredentials( // new AuthScope(null,-1),// new UsernamePasswordCredentials(mUsername,mPassword)); httpResponse httpResponse = clIEnt.execute(getmethod); // statusCode == 200 正常 statusCode = httpResponse.getStatusline().getStatusCode(); Log.d(TAG,"statuscode = " + statusCode); // 处理返回的httpResponse信息 result = retrIEveinputStream(httpResponse.getEntity()); } catch (Exception e) { Log.e(TAG,e.getMessage()); throw new Exception(e); } finally { getmethod.abort(); } return result; }
参数URL: 我们要请求的地址
ClIEnt: 这个可以直接用new DefaulthttpClIEnt(new BasichttpParams()) 来初始化.
这个方法中需要注意RetrIEveinputStream方法,这个是当http请求完成之后,用来处理服务器返回数据的方法,
二. 接受从WCF端传回的数据
protected String retrIEveinputStream(httpentity httpentity) { int length = (int) httpentity.getContentLength(); if (length < 0) length = 10000; StringBuffer stringBuffer = new StringBuffer(length); try { inputStreamReader inputStreamReader = new inputStreamReader( httpentity.getContent(),http.UTF_8); char buffer[] = new char[length]; int count; while ((count = inputStreamReader.read(buffer,length - 1)) > 0) { stringBuffer.append(buffer,count); } } catch (UnsupportedEnCodingException e) { Log.e(TAG,e.getMessage()); } catch (IllegalStateException e) { Log.e(TAG,e.getMessage()); } catch (IOException e) { Log.e(TAG,e.getMessage()); } return stringBuffer.toString(); }
此方法在接受到WCF服务端返回的数据之后, 转换程String类型返回.
附加内容:
请求数据之前封装方法:
private static final String BASE_URL = "http://10.0.2.2:82/BlogcategoryService/"; private static final String EXTENSION = "Json/";; private static final String TAG = "API"; private static final String USER_AGENT = "Mozilla/4.5"; public JsONObject getobject(String sbj) throws JsONException,Exception { return new JsONObject(getRequest(BASE_URL + EXTENSION + sbj)); } public JsONArray getArray(String sbj) throws JsONException,Exception { return new JsONArray(getRequest(BASE_URL + EXTENSION + sbj)); } protected String getRequest(String url) throws Exception { return getRequest(url,new DefaulthttpClIEnt(new BasichttpParams())); }
总结 : 此篇主要说明了http请求的的两个阶段,建立请求跟接受服务器返回的数据,在下篇再主要说明如何处理服务端返回的JsON数据,并把数据显示在UI上面.
总结以上是内存溢出为你收集整理的Android访问WCF服务全部内容,希望文章能够帮你解决Android访问WCF服务所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)