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

 

方式一:

    /// <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();
else
return Guid.NewGuid().ToString(type);
}

//-------------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();
}

WCF服务支持HTTP(get,post)的更多相关文章

  1. 在IIS8添加WCF服务支持

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

  2. 【IIS8】在IIS8添加WCF服务支持

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

  3. WCF服务支持HTTP(get,post)方式请求例子

    https://www.cnblogs.com/li150dan/p/9529413.html /// <summary> /// Http Get请求 /// </summary& ...

  4. C# WCF服务入门

    之前在公司用的服务端是wcf写的,但是没有深入研究,最近找工作,面试的时候好多人看到这个总提问,这里做个复习 就用微软官方上的例子,搭一个简单的wcf服务,分6步 1 定义服务协定也就是契约,其实就是 ...

  5. 轻松搞定Win8 IIS支持SVC 从而实现IIS寄宿WCF服务

    写在前面 为了尝试在IIS中寄宿WCF服务,需要配置IIS支持SVC命令,于是便有了在DOS命令中用到ServiceModelReg.exe注册svc命令. 坑爹的是注册成功后就开始报错.无奈之下两次 ...

  6. IIS10 设置支持wcf服务(.svc)

    感谢: http://www.cnblogs.com/dudu/p/3328066.html 如果提示web.config配置重复的话,很有可能是.net framework版本的问题,把IIS中的版 ...

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

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

  8. 如何让WCF服务更好地支持Web Request和AJAX调用

    WCF的确不错,它大大地简化和统一了服务的开发.但也有不少朋友问过我,说是在非.NET客户程序中,有何很好的方法直接调用服务吗?还有就是在AJAX的代码中(js)如何更好地调用WCF服务呢? 我首先比 ...

  9. 关于WCF服务 http://XXXXXX/XXX/xxx.svc不支持内容类型 application/sop+xml;charset=utf-8 错误解决方法

    有时候用IIS部署一个WCF服务时,无论是在客户端还是在服务端通过地址都能正常访问. 但是当你在客户端添加服务引用时, 怎么也添加不上, 会碰到了如下错误: 好啦. 现在说说怎么解决吧. 其实很简单. ...

随机推荐

  1. Zabbix设置自定义监控项之——监控tcp连接状态

    目录 一.用户自定义参数 二.配置 监控 TCP 连接状态 在实际监控中,除了官方自带的一些监控项,我们很多时候有一些定制化监控,比如特定的服务.TCP 连接状态等等,这时候就需要自定义监控项.自定义 ...

  2. python3之int类的常用方法练习

    int类的常用方法练习 #coding:utf-8 #int类的常用方法 num1 = 18 num2 = -15 #查询创建num1所用的类 print(type(num1)) #num1占用的最小 ...

  3. jenkins 比较好的学习的文章

    来自 :  https://www.cnblogs.com/horizonli/tag/jenkins/

  4. 【设计模式】Composite

    目录 前言 安卓View的实现 View Beyond setContentView setContentView做了什么事情? 如何将xml文件变成对象的? 小结 View的绘制流程 三个流程 三个 ...

  5. Electron使用时拦截HTTP请求的解决方案

    背景 最近在做一个Web和Electron共用一份代码的工程,由于使用到了第三方的库(我们是在线地图),该库的认证方式是请求时加key,并且它在后台会校验referer. 于是问题就来了,Electr ...

  6. 【vuejs】vue数组操作

    问题:两种操作都能给数组添加数据,但是利用下标添加数据不会自动在视图中渲染,这个是和vue自己的规定有关,这里记录一下 网上到原因,这里附转载链接 点我传送 官网相关说明传送门

  7. hashlib以及hmac的日常应用

    首先我们要明白日常的Web网页为了保证数据的安全都会对数据的存储进行一些加密,当我需要在此网站验证时就需要对原有的密码以及账号进行加密此时我们就需要用到hashlib这个框架的一些功能,下面我就来更大 ...

  8. Python列表操作与深浅拷贝(7)——列表深浅拷贝、删除、反转、排序

    列表复制 浅拷贝:简单类型元素全复制,引用类型元素只复制引用 L1 = [3,2,1,[4,5,6],8,'abc'] L1 [3, 2, 1, [4, 5, 6], 8, 'abc'] L2 = L ...

  9. BeanShell实现加密解密功能

    一,在IDEA中写好加密的脚本 二,然后将整个包文件导出,生成jar包 三,将jar包文件放到jmeter的lib/ext目录下 然后在jmeter的BeanShell中引入该类,调用其中的加密方法 ...

  10. 201871010123-吴丽丽《面向对象程序设计(Java)》第十五周学习总结

    201871010123-吴丽丽<面向对象程序设计(Java)>第十五周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ ...