WCF服务端与使用HttpClient的Android客户端简单示例

WCF服务端

Contract

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web;

namespace Contract
{
    /// 
    /// 服务接口
    /// 
    /// 
    /// WebInvoke - 指示服务操作在逻辑上就是调用操作,而且可由Web编程模型调用
    /// WebGet - 指示服务操作在逻辑上就是检索操作,而且可由Web编程模型调用
    /// UriTemplate - 用于服务操作的统一资源标识符(URI)模版。URI模版可以将一个URI或一组URI映射到服务操作
    /// Method - 与操作关联的写作方法,默认为 POST
    /// ResponseFormat - 指定从服务操作发出的响应的格式。Xml或Json
    /// BodyStyle - 指定body里面的封装
    /// 
    [ServiceContract]    
    public interface IWcfService
    {
        /// 
        /// GET - 无参数 - 返回值为字符串数组
        /// 
        /// 
        [OperationContract]
        [WebGet(
            ResponseFormat = WebMessageFormat.Json)]
        List GetStudentNames();

        /// 
        /// GET - 无参数 - 返回值为自定义类型的数组
        /// 
        /// 
        [OperationContract]
        [WebGet(
            ResponseFormat = WebMessageFormat.Json)]
        List GetStudents();

        /// 
        /// GET - 一个参数 - 返回值为int
        /// 
        /// 
        /// 
        [OperationContract]
        [WebGet(
            UriTemplate = "GetStudentAge/{name}",   
            //UriTemplate = "GetStudentAge?name={name}",    //默认形式
            ResponseFormat = WebMessageFormat.Json)]
        int GetStudentAge(string name);

        /// 
        /// GET - 多个参数 - 返回值为自定义格式
        /// 
        /// 
        /// 
        /// 
        /// 
        [OperationContract]
        [WebGet(
            UriTemplate = "CreateStudent/{name}/{birth}/{age}", //UriTemplate中只允许字符串类型的变量
            //UriTemplate = "CreateStudent?name={name}&birth={birth}&age={age}",    //默认形式
            ResponseFormat = WebMessageFormat.Json)]
        Student CreateStudent(string name, string birth, string age);

        /// 
        /// POST - 一个参数 - 返回值为bool
        /// 
        /// 
        /// 
        [OperationContract]
        [WebInvoke(
            UriTemplate = "DeleteStudent",
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        bool DeleteStudent(string name);

        /// 
        /// POST - 多个参数 - 返回值为自定义格式
        /// 
        /// 
        /// 
        /// 
        /// 
        [OperationContract]
        [WebInvoke(
            UriTemplate = "AddStudent",
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        Student AddStudent(string name, string birth, int age);

        /// 
        /// POST - 自定义格式参数 - 返回值为string
        /// 
        /// 
        /// 
        [OperationContract]
        [WebInvoke(
            UriTemplate = "UpdateStudent",
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        string UpdateStudent(Student student);
    }

    [DataContract]
    public class Student 
    {
        private string name;
        [DataMember(Order = 0, Name = "name")]
        public string Name 
        {
            get { return name; }
            set 
            { 
                name = HttpUtility.UrlDecode(value, Encoding.UTF8);
            }
        }

        private string birth;
        [DataMember(Order = 1, Name = "birth")]
        public string Birth
        {
            get { return birth; }
            set { this.birth = value; }
        }

        private int age;
        [DataMember(Order = 1, Name = "age")]
        public int Age
        {
            get { return age; }
            set { this.age = value; }
        }
    }
}

Service

using Contract;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Service
{
    public class WcfService : IWcfService
    {
        public List GetStudentNames()
        {
            Console.WriteLine();
            Console.WriteLine("GetStudentNames()");

            List results = new List();
            results.Add("zhangsan");
            results.Add("李四");
            results.Add("wangwu");
            return results;
        }

        public List GetStudents()
        {
            Console.WriteLine();
            Console.WriteLine("GetStudents()");

            List results = new List();
            results.Add(new Student() { Name = "zhangsan", Birth = "1955-5-48", Age = 56 });
            results.Add(new Student() { Name = "李四", Birth = "1965-6-48", Age = 46 });
            return results;
        }

        public int GetStudentAge(string name)
        {
            Console.WriteLine();
            Console.WriteLine("GetStudentAge(name)");
            Console.WriteLine();
            Console.WriteLine("name = " + name);

            return 22;
        }

        public Student CreateStudent(string name, string birth, string age)
        {
            Console.WriteLine();
            Console.WriteLine("CreateStudent(name,birth,age)");
            Console.WriteLine();
            Console.WriteLine("name = " + name + ", birth = " + birth + ", age = " + age);

            return new Student()
            {
                Name = name,
                Birth = birth,
                Age = Convert.ToInt32(age)
            };
        }

        public bool DeleteStudent(string name)
        {
            name = HttpUtility.UrlDecode(name, Encoding.UTF8);
            Console.WriteLine();
            Console.WriteLine("DeleteStudent(name)");
            Console.WriteLine();
            Console.WriteLine("name = " + name);

            return true;
        }

        public Student AddStudent(string name, string birth, int age)
        {
            Console.WriteLine();
            Console.WriteLine("AddStudent(name,birth,age)");
            Console.WriteLine();
            Console.WriteLine("name = " + name + ", birth = " + birth + ", age = " + age);

            return new Student()
            {
                Name = name,
                Birth = birth,
                Age = age
            };
        }

        public string UpdateStudent(Student student)
        {
            Console.WriteLine();
            Console.WriteLine("UpdateStudent(student)");
            Console.WriteLine();
            Console.WriteLine("name = " + student.Name + " , birth = " + student.Birth);

            return student.Name;
        }
    }
}

Hosting

App.config


  
    
  
  
    
    
      
        
          
        
      
      
        
          
          
          
        
      
    
    
      
        
          
        
      
    
    
      
        
        
          
            
          
        
      
    
  
  
    
  
  
  
    
      
        
          
        
      
    
    
      
    
  

Program.cs
using System;
using System.ServiceModel;

namespace Hosting
{
    class Program
    {
        /// 
        /// 采用自托管的方式发布服务
        /// 
        /// 
        static void Main(string[] args)
        {
            Console.WriteLine("---------------------------------------------------------------");

            ServiceHost host = null;
            try
            {
                host = new ServiceHost(typeof(Service.WcfService));

                host.Opened += host_Opened;

                host.Open();

                //公共服务地址
                foreach (var endPoint in host.Description.Endpoints)
                {
                    Console.WriteLine(endPoint.Address.ToString());
                }

                Console.WriteLine("按任意键终止服务!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.Read();

                if (host != null) 
                {
                    host.Close();
                    host = null;
                }
            }
        }

        static void host_Opened(object sender, EventArgs e)
        {
            Console.WriteLine("Service已经启动");
        }
    }
}

Android客户端

HttpClientThread.java

import android.os.Handler;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class HttpClientThread extends Thread {

    private Handler handler;
    private TextView textView;

    private HttpParams httpParams;
    private HttpClient httpClient;

    public HttpClientThread(Handler handler, TextView textView) {
        this.handler = handler;
        this.textView = textView;

        this.httpClient = getHttpClient();
    }

    @Override
    public void run() {
        String result = "";

        String url = "http://192.168.0.192:8888/service/";

        //GET,无参数,返回值为字符串数组
//        result = doHttpClientGet(url + "GetStudentNames");
//        try {
//            JSONArray array = new JSONArray(result);
//            result = "";
//            for (int i=0; i

MainActivity.java

import android.app.Activity;
import android.os.Handler;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Handler handler = new Handler();

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.text);

        new HttpClientThread(handler, textView).start();
    }   
}

AndroidManifest.xml



参考文档:

  • wcf完美搭建android平台服务之一
  • wcf完美搭建android平台服务之二
  • wcf完美搭建android平台服务之三
  • 在Android调用WCF服务

你可能感兴趣的:(WCF,Android_Network)