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

来源:互联网 发布:python使用手册 编辑:程序博客网 时间:2024/05/18 00:45

WCF服务端

契约Contract

using System.ServiceModel;using System.ServiceModel.Web;namespace Contract{    /// <summary>    /// Android客户端调用的服务接口    /// </summary>    [ServiceContract(Name = "WcfService", Namespace = "http://tempuri.org/")]        public interface IWcfService    {        /// <summary>        /// 客户端访问 url + /TestGet        /// </summary>        /// <returns></returns>        [OperationContract]        [WebGet(            ResponseFormat = WebMessageFormat.Json)]    //默认XML格式        string TestGet();        /// <summary>        /// 客户端访问 url + /TestGet1?name=zhangsan        /// </summary>        /// <param name="name"></param>        /// <returns></returns>        [OperationContract]        [WebGet(            RequestFormat = WebMessageFormat.Json,  //json或xml无影响            ResponseFormat = WebMessageFormat.Json)]        string TestGet1(string name);        /// <summary>        /// 客户端访问 url + /TestGet2?name=zhangsan&age=20        /// </summary>        /// <param name="name"></param>        /// <param name="age"></param>        /// <returns></returns>        [OperationContract]        [WebGet(            RequestFormat = WebMessageFormat.Json,  //json或xml无影响            ResponseFormat = WebMessageFormat.Json)]        string TestGet2(string name, int age);        /// <summary>        /// 客户端访问:        /// GET or POST:url + /TestGetOrPost        /// </summary>        /// <returns></returns>        [OperationContract]        [WebInvoke(            Method = "*",            ResponseFormat = WebMessageFormat.Json)]        string TestGetOrPost();        /// <summary>        /// 客户端访问:        /// GET or POST:url + /TestGetOrPost1/URLEncoder.encode(json, "utf8")        /// </summary>        /// <param name="json"></param>        /// <returns></returns>        [OperationContract]        [WebInvoke(            Method = "*",   //*既可以POST也可以GET            UriTemplate = "TestGetOrPost1/{json}",            RequestFormat = WebMessageFormat.Json,            ResponseFormat = WebMessageFormat.Json)]        string TestGetOrPost1(string json);    }}

服务Service

using Contract;using Newtonsoft.Json.Linq;using System;namespace Service{    public class WcfService : IWcfService    {        public string TestGet()        {            Console.WriteLine();            Console.WriteLine("TestGet()");                        //通知移动端接收成功            return "{\"result\":1}";        }        public string TestGet1(string name)        {            Console.WriteLine();            Console.WriteLine("TestGet1(name)");            Console.WriteLine("name = " + name);            //通知移动端接收成功            return "{\"result\":1}";        }        public string TestGet2(string name, int age)        {            Console.WriteLine();            Console.WriteLine("TestGet2(name, age)");            Console.WriteLine("name = " + name + " , age = " + age);            //通知移动端接收成功            return "{\"result\":1}";        }        public string TestGetOrPost()        {            Console.WriteLine();            Console.WriteLine("TestGetOrPost()");            //通知移动端接收成功            return "{\"result\":1}";        }        public string TestGetOrPost1(string json)        {            Console.WriteLine();            Console.WriteLine("TestGetOrPost1(json)");            JObject obj = JsonHelper.ReadJson(json);            if (obj == null)            {                return "{\"result\":0}";            }            Console.WriteLine();            Console.WriteLine(obj.ToString());            string name = JObjectReader.GetName(obj);            int? age = JObjectReader.GetAge(obj);            if (string.IsNullOrEmpty(name) || age.HasValue == false)            {                return MsgResult.FailureOfErrorParam();            }            return "{\"name\":\"" + name + "\", \"age\":" + age + "}";        }    }}

控制台程序Hosting

App.config

<?xml version="1.0" encoding="utf-8"?><configuration>  <startup>    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>  </startup>  <system.serviceModel>    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>    <behaviors>      <endpointBehaviors>        <behavior name="webHttpBehavior">          <webHttp helpEnabled="true"/>        </behavior>      </endpointBehaviors>      <serviceBehaviors>        <behavior name="webHttpBehavior">          <serviceMetadata httpGetEnabled="true" httpGetUrl="metadata"/>          <serviceDebug includeExceptionDetailInFaults="true"/>          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>        </behavior>      </serviceBehaviors>    </behaviors>    <bindings>      <webHttpBinding>        <binding name="webHttpBinding" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>        </binding>      </webHttpBinding>    </bindings>    <services>      <service behaviorConfiguration="webHttpBehavior" name="Service.WcfService">        <endpoint address="/" behaviorConfiguration="webHttpBehavior"          binding="webHttpBinding" bindingConfiguration="webHttpBinding"          name="WcfService" contract="Contract.IWcfService" />        <host>          <baseAddresses>            <add baseAddress="http://localhost:8888/service" />          </baseAddresses>        </host>      </service>    </services>  </system.serviceModel>  <system.webServer>    <modules runAllManagedModulesForAllRequests="true"/>  </system.webServer>  <!--保存具体的错误信息到svclog文件中-->  <system.diagnostics>    <sources>      <source name="System.ServiceModel" switchValue="Warning" propagateActivity="true">        <listeners>          <add name="xml" />        </listeners>      </source>    </sources>    <sharedListeners>      <add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="F:\wcf.svclog" />    </sharedListeners>  </system.diagnostics></configuration>

Program.cs

using System;using System.ServiceModel;using Service;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();                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客户端

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 HttpURLConnectionThread(textView, handler).start();    }}

HttpURLConnectionThread.java

import android.os.Handler;import android.widget.TextView;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONException;import org.json.JSONStringer;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLDecoder;import java.net.URLEncoder;public class HttpURLConnectionThread extends Thread {    private TextView textView;    private Handler handler;    public HttpURLConnectionThread (TextView textView, Handler handler) {        this.textView = textView;        this.handler = handler;    }    @Override    public void run() {     //        doGet("http://www.imooc.com/api/teacher?type=4&num=30");  //网络服务//        doGet("http://192.168.1.222:8888/service/TestGet");   //本地服务:无参数//        doGet("http://192.168.1.222:8888/service/TestGet2?name=zhangsan&age=20");  //本地服务:两个参数        try {            doGet("http://192.168.1.222:8888/service/TestGet2?name="+URLEncoder.encode("张三", "utf-8")+"&age=20");  //本地服务:两个参数(带中文)        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }//        doGet("http://192.168.1.222:8888/service/TestGetOrPost");  //本地服务:无参数//        doPost("http://192.168.1.222:8888/service/TestGetOrPost", "");  //本地服务,无参数//        try {//            JSONStringer json = new JSONStringer()//                    .object()//                    .key("name").value("zhangsan")//                    .key("age").value(28)//                    .endObject();//            doGet("http://192.168.1.222:8888/service/TestGetOrPost1/"    //本地服务,一个参数//                    + URLEncoder.encode(json.toString(), "utf8"));//   doPost("http://172.16.24.253:8888/service/TestGetOrPost1/"                + URLEncoder.encode(json.toString(), "utf8"), "");  //本地服务,一个参数//        } catch (JSONException e) {//            e.printStackTrace();//        } catch (UnsupportedEncodingException e) {//            e.printStackTrace();//        }    }    private void doPost(String url, String json) {        try {            URL httpUrl = new URL(url);            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();            connection.setRequestMethod("POST");            connection.setDoOutput(true);            connection.setReadTimeout(5000);            OutputStream outputStream = connection.getOutputStream();            outputStream.write(json.getBytes());            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));            StringBuilder sb = new StringBuilder();            String str;            while ((str = reader.readLine()) != null) {                sb.append(str);            }            final String result = sb.toString();            handler.post(new Runnable() {                @Override                public void run() {                    textView.setText(result);                }            });        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    private void doGet(String url) {        try {            URL httpUrl = new URL(url);            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();            connection.setRequestMethod("GET");            connection.setReadTimeout(5000);            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));            StringBuilder sb = new StringBuilder();            String str;            while ((str=reader.readLine())!=null) {                sb.append(str);            }            final String result = sb.toString();            handler.post(new Runnable() {                @Override                public void run() {                    textView.setText(result);                }            });        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}
0 0
原创粉丝点击