经过多日努力, 终于勉强弄明白了Android访问WCF服务的方法.
服务端实现
一, 实现服务.
操作契约
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- [WebInvoke(
- BodyStyle = WebMessageBodyStyle.WrappedRequest,
- ResponseFormat = WebMessageFormat.Json,
- RequestFormat = WebMessageFormat.Json)]
- string getMsg();
- [OperationContract]
- [WebInvoke(
- BodyStyle = WebMessageBodyStyle.WrappedRequest,
- ResponseFormat = WebMessageFormat.Json,
- RequestFormat = WebMessageFormat.Json)]
- string setMsg(string msg);
- [OperationContract]
- [WebInvoke(
- BodyStyle = WebMessageBodyStyle.WrappedRequest,
- ResponseFormat = WebMessageFormat.Json,
- RequestFormat = WebMessageFormat.Json)]
- Data getData();
- [OperationContract]
- [WebInvoke(
- BodyStyle = WebMessageBodyStyle.WrappedRequest,
- ResponseFormat = WebMessageFormat.Json,
- RequestFormat = WebMessageFormat.Json)]
- Data setData(Data data);
- }
以上的服务包含了不带参数和带参数访问的形式. 其中Data类的定义如下
- [DataContract]
- public class Data
- {
- [DataMember (Name = "Name")]
- public string Name { get; set; }
- [DataMember(Name = "age")]
- public int age { get; set; }
- [DataMember(Name = "msg")]
- public string msg { get; set; }
- [DataMember(Name = "array")]
- public string[] array { get; set; }
- }
实现服务类
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.Text;
- namespace Host
- {
- // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service”。
- public class Service : IService
- {
- #region IService Members getMsg
- public string getMsg()
- {
- Console.WriteLine("getMsg service has bean statred!");
- return string.Format("现在服务器时间{0}", DateTime.Now);
- }
- #endregion
- #region IService Members setMsg
- public string setMsg(string msg)
- {
- Console.WriteLine("setMsg service has bean started!");
- return string.Format("现在服务器时间{0}, 消息内容{1}", DateTime.Now, msg);
- }
- #endregion
- #region IService Members getData
- public Data getData()
- {
- Console.WriteLine("getData service has bean started!");
- Data data = new Data();
- data.Name = "Mush Service";
- data.age = 20;
- data.msg = "This is a data form service_HelloData";
- data.array = new string[3] { "string1", "string2", "string3" };
- return data;
- }
- #endregion
- #region IService Members setData
- public Data setData(Data data)
- {
- Console.WriteLine("setData service has bean started!");
- data.msg = "This MSG has bean changed by service!!!";
- return data;
- }
- #endregion
- }
- }
二, 配置服务
在配置文件的behaviors结点下增加如下内容
- <endpointBehaviors>
- <behavior name="json">
- <enableWebScript />
- </behavior>
- </endpointBehaviors>
修改默认终结点配置
- <endpoint binding="webHttpBinding" contract="Host.IService" behaviorConfiguration="json">
- <identity>
- <dns value="localhost"/>
- </identity>
- </endpoint>
三, 实现自我寄宿
- static void Main(string[] args)
- {
- using (ServiceHost host = new ServiceHost(typeof(Host.Service)))
- {
- host.Open();
- Console.WriteLine("Host is started!!! Press any ENTER to stop.");
- Console.ReadLine();
- host.Close();
- }
- }
Android客户端实现
在Android客户端需要按照数据契约规定的数据类型实现一个数据类
- public class Data {
- private String Name;
- private int age;
- private String msg;
- private String[] array;
- public String getName() {
- return Name;
- }
- public void setName(String name) {
- Name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public String[] getArray() {
- return array;
- }
- public void setArray(String[] array) {
- this.array = array;
- }
- }
然后结合实际情况编写事物层代码
以下给出一个带参访问web服务的常见用法
- /**
- * @param url 服务的完整地址
- * @param data 数据对象
- * @param contentType Request的ContentType
- * @return 返回的json字符串
- */
- public String doPost(String url, Data data, String contentType) {
- String strResp = "";
- HttpPost request = new HttpPost(url);
- request.setHeader("Accept", "application/json");
- request.setHeader("Content-type", "application/json");
- // 组织json
- JSONStringer vehicle;
- try {
- vehicle = new JSONStringer().object().key("data").object()
- .key("Name").value(data.getName()).key("age").value(data.getAge())
- .key("array").value(data.getArray()).key("msg").value(data.getMsg())
- .endObject().endObject();
- StringEntity entity = new StringEntity(vehicle.toString());
- request.setEntity(entity);
- // 向WCF服务发送请求
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpResponse response = httpClient.execute(request);
- // 判断是否成功
- if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK)
- strResp = EntityUtils.toString(response.getEntity());
- Log.d("WebInvoke", "Saving : "
- + response.getStatusLine().getStatusCode());
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // Reload plate numbers
- return strResp;
- }
判断访问web服务是否成功通过
- response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
即可
源码下载:
http://blog.csdn.net/btyh17mxy/article/details/7993111