Android访问WCF服务

原文链接: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", ResponseFormat = WebMessageFormat.Json, 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, 0, length - 1)) > 0) { stringBuffer.append(buffer, 0, 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上面.

相关文章