wcf 接收post数据_WCF服务支持HTTP(get,post)方式请求例子

本文提供了使用WCF服务处理HTTP GET和POST请求的示例代码。包括发送GET请求,发送POST请求,并实现了HTTP幂等性以防止重复请求,通过在请求头中添加唯一ID。此外,还提供了一个生成不同格式GUID的方法。
摘要由CSDN通过智能技术生成

///

///Http Get请求///

/// 请求地址

/// 请求参数

/// 为防止重复请求实现HTTP幂等性(唯一ID)

///

public static string SendGet(string url, string postData, stringtrackId)

{if (string.IsNullOrEmpty(trackId)) return null; //trackId = Guid.NewGuid().ToString("N");

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + (postData == "" ? "" : "?") +postData);

httpWebRequest.Method= "GET";

httpWebRequest.ContentType= "text/html;charset=UTF-8";

httpWebRequest.Headers.Add("track_id:" +trackId);

WebResponse webResponse=httpWebRequest.GetResponse();

HttpWebResponse httpWebResponse=(HttpWebResponse)webResponse;

System.IO.Stream stream=httpWebResponse.GetResponseStream();

System.IO.StreamReader streamReader= newSystem.IO.StreamReader(stream, Encoding.UTF8);string result = streamReader.ReadToEnd(); //请求返回的数据

streamReader.Close();

stream.Close();returnresult;

}///

///Http Post请求///

/// 请求地址

/// 请求参数(json格式请求数据时contentType必须指定为application/json)

/// 为防止重复请求实现HTTP幂等性(唯一ID)

///

public static string SendPost(string postUrl, string postData, string trackId, string contentType = "application/x-www-form-urlencoded")

{if (string.IsNullOrEmpty(trackId)) return null; //trackId = Guid.NewGuid().ToString("N");

byte[] byteArray =System.Text.Encoding.UTF8.GetBytes(postData);

HttpWebRequest httpWebRequest=(HttpWebRequest)WebRequest.Create(postUrl);

httpWebRequest.Method= "POST";

httpWebRequest.ContentType=contentType;

httpWebRequest.ContentLength=byteArray.Length;

httpWebRequest.Headers.Add("track_id:" +trackId);

System.IO.Stream stream=httpWebRequest.GetRequestStream();

stream.Write(byteArray,0, byteArray.Length); //写入参数

stream.Close();

HttpWebResponse httpWebResponse=(HttpWebResponse)httpWebRequest.GetResponse();

System.IO.StreamReader streamReader= newSystem.IO.StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);string result = streamReader.ReadToEnd(); //请求返回的数据

streamReader.Close();returnresult;

}///

///生成唯一标识符///

/// 格式:N,D,B,P,X

///

public static string GetGuid(string type = "")

{//Guid.NewGuid().ToString();//9af7f46a-ea52-4aa3-b8c3-9fd484c2af12//Guid.NewGuid().ToString("N");//e0a953c3ee6040eaa9fae2b667060e09//Guid.NewGuid().ToString("D");//9af7f46a-ea52-4aa3-b8c3-9fd484c2af12//Guid.NewGuid().ToString("B");//{734fd453-a4f8-4c5d-9c98-3fe2d7079760}//Guid.NewGuid().ToString("P");//(ade24d16-db0f-40af-8794-1e08e2040df3)//Guid.NewGuid().ToString("X");//{0x3fa412e3,0x8356,0x428f,{0xaa,0x34,0xb7,0x40,0xda,0xaf,0x45,0x6f}}

if (type == "")returnGuid.NewGuid().ToString();else

returnGuid.NewGuid().ToString(type);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值