zoukankan      html  css  js  c++  java
  • WCF+restful

    服务端代码:hosting方式

    View Code
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    
    namespace Hosting
    {
        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();
                }
            }
        }
    
        [ServiceContract]
        public interface IAccountJsonService
        {
            [OperationContract(Name = "GetAccountDataJson")]
            [WebInvoke(Method = "*", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetAccountData", BodyStyle = WebMessageBodyStyle.Bare)]
            List<Account> GetAccountData();
    
            [OperationContract(Name = "SendMessageJson")]
            [WebInvoke(Method = "get", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SendMessage")] // UriTemplate = "SendMessage/?Message={Message}"
            string SendMessage(string Message);
    
            [OperationContract(Name = "SendMessage2Json")]
            [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SendMessage2")]
            string SendMessage2(ReqData data);
    
            [OperationContract(Name = "GetMessageDataJson")]
            [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetMessageData", BodyStyle = WebMessageBodyStyle.Bare)]
            ReqData GetMessageData();
        }
    
        [ServiceContract]
        public interface IAccountXmlService
        {
            [OperationContract(Name = "GetAccountDataXml")]
            [WebGet(RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "GetAccountData", BodyStyle = WebMessageBodyStyle.Bare)]
            List<Account> GetAccountData();
    
            [OperationContract(Name = "SendMessageXml")]
            [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, UriTemplate = "SendMessage/{Message}", BodyStyle = WebMessageBodyStyle.Bare)]
            string SendMessage(string Message);
        }
    
    
        public class AccountService : IAccountJsonService, IAccountXmlService
        {
            public List<Account> GetAccountData()
            {
                return MockAccount.AccountList;
            }
            public string SendMessage(string Message)
            {
                return " Message:" + Message;
            }
    
            public string SendMessage2(ReqData data)
            {
                return data.Message + "message";
            }
    
            public ReqData GetMessageData()
            {
                return new ReqData() { Message = "feww" };
            }
    
        }
        [DataContract]
        public class ReqData
        {
            [DataMember]
            public string Message { get; set; }
        }
    
        [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;
                }
            }
        }
    }

    配置文件:app.config

    <?xml version="1.0"?>
    <configuration>
      <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="" binding="webHttpBinding"  contract="Hosting.IAccountJsonService" behaviorConfiguration="WebHttpBindingBehavior"/>
            <host>
              <baseAddresses>
                <add baseAddress="http://127.0.0.1:82/AccountService" />
              </baseAddresses>
            </host>
          </service>
        </services>
      </system.serviceModel>
    </configuration>
    

     客户端调用:利用webClient和httpWebRequest、HttpWebResponse请求数据

    View Code
    WebClient cli = new WebClient();
                string json = cli.DownloadString(new Uri("http://127.0.0.1:82/AccountService/GetAccountData"));
    
    
                string strjson = "{\"Message\":\"feww\"}";
                byte[] bytes = Encoding.ASCII.GetBytes(strjson);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://127.0.0.1:82/AccountService/SendMessage2"));
                request.Method = "POST";
                request.ContentType = "application/json";//"application/x-www-form-urlencoded";//"application/json";//
                request.ContentLength = bytes.Length;
                using (Stream rstream = request.GetRequestStream())
                {
                    rstream.Write(bytes, 0, bytes.Length);
                }
                HttpWebResponse res = (HttpWebResponse)request.GetResponse();
    
                string strresult = "";
                Stream receivestream = res.GetResponseStream();
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader sr = new StreamReader(receivestream, encode);
                char[] read = new char[256];
                int count = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    string str = new string(read, 0, count);
                    strresult += str;
                    count = sr.Read(read, 0, 256);
                }
  • 相关阅读:
    【并发】基于 @Async和 CompletableFuture 实现并发异步操作
    【HTTP】使用 RestTemplete 实现 post请求
    【AICC】2019训练营笔记
    【Hadoop】CDH、Presto配置问题
    【Linux】文件拷贝-Linux当前目录所有文件移动到上一级目录(转)
    【Linux】linux ln文件夹的链接(转)
    【Hadoop】新建hadoop用户以及用户组,给予sudo权限(转)
    【Centos】桌面安装(转)
    【CentOS7】CentOS7各个版本镜像下载地址(转)
    【Spark】ScalaIDE运行spark,A master URL must be set in your configuration
  • 原文地址:https://www.cnblogs.com/liqiao/p/2705569.html
Copyright © 2011-2022 走看看