首页 > 代码库 > wcf webHttpBinding Post

wcf webHttpBinding Post

一直在为安卓和苹果写服务,刚开始的时候全用的Get请求用url传所有的参数,由于url长度的限制大的数据量

无法传到服务器,提交图片什么的就更不用说了,后来用的POST请求,记录一下,做了一个很简单的小例子:

c#源代码提供大家下载 10Solution4.rar

ios代码 IOSHttpPostDemo.rar

 开始做吧!

1建一个空工程Solution4,添加一个类库WcfSerDemo引入

System.ServiceModel  和System.ServiceModel.Web两个类库

建一个接口IMyWcfServerMethod

?
[ServiceContract]
public interface IMyWcfServerMethod
{    
    [OperationContract, WebInvoke(Method = "POST", UriTemplate = "postMostStr/{streamLength}", BodyStyle = WebMessageBodyStyle.Bare)]
    string postMostStr(string streamLength, Stream getStream);
 
    //实验一下接收
    [OperationContract, WebInvoke( Method="GET", UriTemplate = "postText")]
    string postText();
}

我们只用 postMostStr这个方法它是以POST形式接收的Url只要一个参数就是传过来的byte的长度

那个Stream类型的台数就是Post过来的数据

建一个类实现这个接口MyWcfServerMethodFace

?
public class MyWcfServerMethodFace:IMyWcfServerMethod
    {
        public string postMostStr(string streamLength, System.IO.Stream getStream)
        {
            try
            {  
                int byLength=Convert.ToInt32(streamLength);
                byte[] resultByte = new byte[byLength];
                getStream.Read(resultByte, 0, resultByte.Length);//把接收的stream写到resultByte
                Console.WriteLine(Encoding.UTF8.GetString(resultByte));//把收到的数据输出到控制台
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("success!");
            return "success!";
        }
 
        public string postText()
        {
            Console.WriteLine("text!");
            return "text success";
            
        }
    }

好了契约就写好了,宿主程序就用控制台程序

加一个控制程序

引入System.ServiceModel 和 WcfSerDemo

配制App.config

?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <bindings>
      <webHttpBinding><!--这个是接收大数据加的-->
        <binding name="webBinding" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                        maxArrayLength="2147483647" maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647"/>
        </binding>
      </webHttpBinding>     
    </bindings>
 
    <behaviors>
      <serviceBehaviors>
        <behavior name="mySerBeh">                  
          <serviceMetadata httpGetUrl="mex" httpGetEnabled="true"/>                      
          <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
 
      <endpointBehaviors>
        <behavior name="webHttpendBehavior">
          <webHttp></webHttp>
        </behavior>
      </endpointBehaviors>
    </behaviors>
 
    <services>
      <service name="WcfScrverDemo.MyWcfServerMethodFace" behaviorConfiguration="mySerBeh">
        <host>
          <baseAddresses>
            <add baseAddress="http://LocalHost:7789/MySericeDemo"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="webBinding" contract="WcfScrverDemo.IMyWcfServerMethod" behaviorConfiguration="webHttpendBehavior"></endpoint>
      </service>
    </services>
 
  </system.serviceModel>
</configuration>

在定app.config的时候要注意大小写

让这个服务跑起来吧在控件台应用程序 的Main里加上

using System.ServiceModel;
using WcfScrverDemo;

?
<br><br><br><br><br>static void Main(string[] args)
        {
             
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(MyWcfServerMethodFace)))
                {
                    host.Opened += delegate
                    {
                        Console.WriteLine("server running....");
                    };
                    host.Open();
                    Console.ReadLine();
 
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
        }

服务就好了,运行一下吧

下面就开使定客户端了

我们也用控件台应用程序来做客户端:

建一个客户端程序WcfwebHttpClient

回为用的是webHttpBinding我们可以直接传url就ok了,不用配制app.config

很简单的在Main里加上

?
static void Main(string[] args)
        {
            try
            {
                string strPost = "小妞,给大爷笑一个,不笑,那大爷给你笑一个,我和超人唯一的区别就是我把内裤穿里边了." +
                                 "我的饭量你是知道的,而且我也不爱吃烤鸭,所以吃了四只我就吃不下去了,我就说:实在" +
                                 "不能吃了,待会儿回家还要吃饭呢。天堂这儿还有一牌子:天堂周围四百米严禁摆摊!上帝" +
                                 "坐那正抽烟呢。上帝说,必须好好招待,这么些年好容易有个说相声的上了天堂了。一巴掌" +
                                 "宽护心毛,还纹一条带鱼。《<span>金 梅</span>》里唐僧取经那会儿…… 三十多岁没结婚,北京的媒婆" +
                                 "界就轰动了!骑着脖子拉屎,拉干的我拨下去,拉稀的我擦干了,可是他,骑着脖子拉痢疾!" +
                                 "说相声讲究说学逗唱,当你有口吃就不能说相声。,比如你报时,如果你有口吃就出现这样情况" +
                                 "。现在播报北....北...北京...时.. 时....时间...七....七..七点,靠,我一看表都八点半了  ";
                byte[] buffer = Encoding.UTF8.GetBytes(strPost);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://LocalHost:7789/MySericeDemo/postMostStr/" + buffer.Length);
                request.Method = "POST";
                request.ContentType = "text/plain";
 
                request.ContentLength = buffer.Length;
                Stream requestStram = request.GetRequestStream();
                requestStram.Write(buffer, 0, buffer.Length);
                requestStram.Close();
 
                Stream getStream = request.GetResponse().GetResponseStream();
 
                byte[] resultByte = new byte[200];
                getStream.Read(resultByte, 0, resultByte.Length);
 
                Console.WriteLine(Encoding.UTF8.GetString(resultByte));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

  跑一下看看什么效果吧

看一看服务有输出 吗

 

看一看客户端有没有反回

再看一下ios的代码

?
NSString *myString=@"郭:新年新气象,在这里我们代表512的全体室员向大家拜年了,新年快乐,谢谢各位的捧场,支持于:过年好郭:小孩儿们喜欢过年,都盼着过年,岁数大了就这么回事,那会儿来说穿新衣服、吃好吃的现在对我们来说没这个概念于:现在不盼着这个了郭:小时候盼着给红包,给钱,十块二十块钱,乐的跟什么似的于:那就不少啦郭:那天在寝室聊天,他们家亲戚多于:人多郭:一到春节对他来说收获的季节到了,家里人来了,亲戚来了,朋友来了,谦儿呢?于:都找我郭:呦呦呦,有长个儿了,掏出来了郭:给呀,碎钱于:我静弄点零钱了合着,还挨一句骂,您着把它连起来说成不成啊";
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat: @"http://10.0.3.5:7789/MySericeDemo/postMostStr/%d",[[myString dataUsingEncoding:NSUTF8StringEncoding] length]]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"text/plain" forHTTPHeaderField:@"Content-type"];
     
     
     
    [request setValue:[NSString stringWithFormat:@"%d",[myString length]]  forHTTPHeaderField:@"Content-length"];
     
    [request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];
     
    [NSURLConnection connectionWithRequest:request delegate:self];

  

 

 

好了,简单的小例子就ok了