Android访问WCF服务(使用json实现参数传递)

本文详细介绍了如何在Android客户端通过JSON进行参数传递,访问WCF服务。首先,服务端实现了操作契约和服务类,并在配置文件中设置了相关行为。而在Android端,根据数据契约创建了数据类,并提供了带参数访问Web服务的示例代码,通过判断访问状态来确保服务调用成功。附有源码下载链接,包括WCF服务端和Android客户端代码。
摘要由CSDN通过智能技术生成

经过多日努力, 终于勉强弄明白了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

即可


源码下载:

WCF服务端.

Android客户端.


评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值