方式一:

    /// <summary>/// Http Get请求/// </summary>/// <param name="url">请求地址</param> /// <param name="postData">请求参数</param> /// <param name="result">返回结果</param>/// <returns></returns>public static bool WebHttpGet(string url, string postData, out string result){try{HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + (postData == "" ? "" : "?") + postData);httpWebRequest.Method = "GET";httpWebRequest.ContentType = "text/html;charset=UTF-8";WebResponse webResponse = httpWebRequest.GetResponse();HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;System.IO.Stream stream = httpWebResponse.GetResponseStream();System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.GetEncoding("UTF-8"));result = streamReader.ReadToEnd(); //请求返回的数据
            streamReader.Close();stream.Close();return true;}catch (Exception ex){result = ex.Message;return false;}}/// <summary>/// Http Post请求/// </summary>/// <param name="postUrl">请求地址</param>/// <param name="postData">请求参数(json格式请求数据时contentType必须指定为application/json)</param>/// <param name="result">返回结果</param>/// <returns></returns>public static bool WebHttpPost(string postUrl, string postData, out string result, string contentType = "application/x-www-form-urlencoded"){try{byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);httpWebRequest.Method = "POST";httpWebRequest.ContentType = contentType;httpWebRequest.ContentLength = byteArray.Length;using (System.IO.Stream stream = httpWebRequest.GetRequestStream()){stream.Write(byteArray, 0, byteArray.Length); //写入参数
            }HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;using (System.IO.Stream responseStream = httpWebResponse.GetResponseStream()){System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));result = streamReader.ReadToEnd(); //请求返回的数据
                streamReader.Close();}return true;}catch (Exception ex){result = ex.Message;return false;}              }

方式二:

    /// <summary>/// Http Get请求/// </summary>/// <param name="url">请求地址</param> /// <param name="postData">请求参数</param> /// <param name="trackId">为防止重复请求实现HTTP幂等性(唯一ID)</param>/// <returns></returns>public static string SendGet(string url, string postData, string trackId){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 = new System.IO.StreamReader(stream, Encoding.UTF8);string result = streamReader.ReadToEnd(); //请求返回的数据
        streamReader.Close();stream.Close();return result;}/// <summary>/// Http Post请求/// </summary>/// <param name="postUrl">请求地址</param>/// <param name="postData">请求参数(json格式请求数据时contentType必须指定为application/json)</param>/// <param name="trackId">为防止重复请求实现HTTP幂等性(唯一ID)</param>/// <returns></returns>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 = new System.IO.StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);string result = streamReader.ReadToEnd(); //请求返回的数据
        streamReader.Close();return result;}/// <summary>/// 生成唯一标识符/// </summary>/// <param name="type">格式:N,D,B,P,X</param>/// <returns></returns>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 == "")return Guid.NewGuid().ToString();elsereturn Guid.NewGuid().ToString(type);}

View Code

//-------------WCF服务端web.config配置如下:----------------

 <system.serviceModel>    <services><service name="WCFService.WebUser"> <!--WCF中提供了Web HTTP访问的方式--><endpoint binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="WCFService.IWebUser" />  <!--提供WCF服务 , 注意address='Wcf',为了区分开与Web HTTP的地址,添加引用之后会自动加上的--><endpoint address="Wcf" binding="basicHttpBinding" contract="WCFService.IWebUser"/></service></services><behaviors> <!--WCF中提供了Web HTTP的方式--><endpointBehaviors><behavior name="WebBehavior"><webHttp helpEnabled="true" /></behavior></endpointBehaviors> <!--WCF中提供了Web HTTP的方式--><serviceBehaviors><behavior> <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false --><serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>  <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 --><serviceDebug includeExceptionDetailInFaults="false"/></behavior></serviceBehaviors></behaviors><protocolMapping><add binding="basicHttpsBinding" scheme="https" /></protocolMapping>    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /></system.serviceModel>

//-------------WCF服务-------------

namespace WCFService
{// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IWebUser”。
    [ServiceContract]public interface IWebUser{[OperationContract][WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ShowName?name={name}")]string ShowName(string name);[OperationContract][WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/ShowNameByPost/{name}")]string ShowNameByPost(string name);}
}

//-----------客户端传统方式和web http方式调用----------------

   public static void Main(string[] args){                   WebUserClient webUser = new WebUserClient();Console.WriteLine("请输入姓名!");string webname = Console.ReadLine();string webresult = webUser.ShowName(webname);Console.WriteLine(webresult);Console.WriteLine("请输入姓名!");string getData = Console.ReadLine();string apiGetUrl = "http://localhost:8423/WebUser.svc/ShowName";string jsonGetMsg = string.Empty;bool strGetResult = WebHttpGet(apiGetUrl, "name=" + getData, out jsonGetMsg);Console.WriteLine("请求结果:" + strGetResult + ",返回结果:" + jsonGetMsg);Console.WriteLine("请输入姓名!");string postData = Console.ReadLine();string apiPostUrl = "http://localhost:8423/WebUser.svc/ShowNameByPost";string jsonPostMsg = string.Empty;bool strPostResult = WebHttpPost(apiPostUrl, "/" + postData, out jsonPostMsg);Console.WriteLine("请求结果:" + strPostResult + ",返回结果:" + jsonPostMsg);Console.ReadLine();}

转载于:https://www.cnblogs.com/li150dan/p/9529413.html

WCF服务支持HTTP(get,post)方式请求例子相关推荐

  1. 在IIS8添加WCF服务支持

    最近在做Silverlight,Windows Phone应用移植到Windows 8平台,在IIS8中测试一些传统WCF服务应用,发现IIS8不支持WCF服务svc请求,后来发现IIS8缺少对WCF ...

  2. 基于 cz88 纯真IP数据库开发的 IP 解析服务 - 支持 http 协议请求或 rpc 协议请求,也支持第三方包的方式引入直接使用

    cz88 基于 cz88 纯真IP数据库开发的 IP 解析服务 - 支持 http 协议请求或 rpc 协议请求,也支持第三方包的方式引入直接使用 Go 语言编写 进程内缓存结果,重复的 ip 查询响 ...

  3. SSH远程管理及sshd服务支持验证方式

    一.SSH远程管理 1.●SSH定义 SSH(Secure Shell)是一种安全通道协议,主要用来实现字符界面的远程登录.远程复制等功能. SSH协议对通信双方的数据传输进行了加密处理,其中包括用户 ...

  4. java cxf 调用wcf接口_JAVA 调用 WCF 服务流程

    1.  将 WCF 服务发布到 Windows 服务(或者 IIS) 此步骤的目的是为 WCF 服务搭建服务器,从而使服务相关的 Web Services 可以被 JAVA 客户端程序调用,具体步骤参 ...

  5. WCF技术剖析之五:利用ASP.NET兼容模式创建支持会话(Session)的WCF服务

    原文:WCF技术剖析之五:利用ASP.NET兼容模式创建支持会话(Session)的WCF服务 在<基于IIS的WCF服务寄宿(Hosting)实现揭秘>中,我们谈到在采用基于IIS(或者 ...

  6. 实现在GET请求下调用WCF服务时传递对象(复合类型)参数

    WCF实现RESETFUL架构很容易,说白了,就是使WCF能够响应HTTP请求并返回所需的资源,如果有人不知道如何实现WCF支持HTTP请求的,可参见我之前的文章<实现jquery.ajax及原 ...

  7. ajax反序列化出错,将数据从jquery ajax请求传递给wcf服务失败了反序列化?

    我使用下面的代码来调用wcf服务.如果我调用不带参数的(测试)方法,但返回一个字符串,它工作正常.如果我一个参数添加到我的方法,我得到一个奇怪的错误:将数据从jquery ajax请求传递给wcf服务 ...

  8. Silverlight与WCF之间的通信(4)silverlight以net.tcp方式调用console上寄宿的wcf服务

    (由于最近是针对一个demo进行的研究,在之前公开过代码结构,这里只是对需要改动的地方加以说明) WCF4.0使得编写wcf服务不再那么复杂,去掉了许多的配置信息,客户端只需要一个服务地址,便可在系统 ...

  9. WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载]

    原文:WCF技术剖析之二十九:换种不同的方式调用WCF服务[提供源代码下载] 我们有两种典型的WCF调用方式:通过SvcUtil.exe(或者添加Web引用)导入发布的服务元数据生成服务代理相关的代码 ...

最新文章

  1. Yii学习笔记【3】
  2. Calc3: Vector Fields
  3. 有趣但是没有用的linux命令
  4. range和xrange的区别
  5. 利用python爬虫(part8)--Xpath路径表达式
  6. 李洪强经典面试题37
  7. 【转载】Java线程池详解
  8. 转,docker学习笔记
  9. 用 Python 实现植物大战僵尸代码!
  10. django请求和响应
  11. 零基础学python实战-苦苦发愁学习Python?让你享受 7天 掌握Python的感觉
  12. 生态系统类型空间分布数据/土地利用数据/植被类型数据/NPP数据/土壤侵蚀数据/土壤质地分类/降雨量栅格数据
  13. 使用正则表达式写网易通行证
  14. 403 Forbidden nginx/1.6.2
  15. 作为一个程序员对特修斯之船的理解
  16. 为了不被裁之NVMe-MI oob
  17. win10账号被锁定如何解决
  18. 300mm直径硅片湿洗槽出水口设计
  19. 10岁娃获“信息学奥赛”省一等奖
  20. 2021年信创产业融资分析报告

热门文章

  1. golang map的定义语法
  2. k8s使用kubectl命令部署nginx并以nodeport方式暴露端口
  3. Python Django创建项目命令
  4. 请解释一下TreeMap
  5. Sublime Text shift+ctrl妙用、Sublime Text快捷组合键大全
  6. linux history 看更多历史记录_Linux历史记录history常用技巧
  7. java虚拟机类加载机制_《深入理解java虚拟机》学习笔记一/类加载机制
  8. ajax jq 图片上传请求头_全面分析前端的网络请求方式:Ajax ,jQuery ,axios,fetch
  9. java解决特殊字符输出
  10. 在eclipse中查看Android源代码