Csharp:HttpWebRequest or HttpClient
/// <summary>
/// Define other methods and classes here
/// </summary>
/// <param name="url"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static Task<string> MakeAsyncRequest(string contentType, string contenttxt, string mobile)
{
string url = "http://www.dusystem.com/UserServiceAPI";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = WebRequestMethods.Http.Post; //get
request.Timeout = 20000;
request.Proxy = null;
byte[] data = System.Text.Encoding.GetEncoding("gbk").GetBytes("geovindu"); //System.Text.UnicodeEncoding.ASCII.GetBytes("geovindu");//UTF8
Base64Encoder myEncoder = new Base64Encoder(data);
StringBuilder sb = new StringBuilder();
sb.Append(myEncoder.GetEncoded());
string msg = UrlEncode(contenttxt);
string content = string.Format("method={0}&isLongSms={1}&username={2}&password={3}&smstype={4}&mobile={5}&content={6}", "MS", 0, "geovindu", sb.ToString(), 0, mobile, msg);//
byte[] bytes = Encoding.GetEncoding("gbk").GetBytes(content);
request.ContentLength = bytes.Length;
Stream os = request.GetRequestStream();
//req.GetResponseAsync(); os.Write(bytes, 0, bytes.Length);
os.Close();
//System.Net.WebResponse resp = req.GetResponse();
WebResponse resp = request.GetResponse(); Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null); return task.ContinueWith(t => ReadStreamFromResponse(resp, content));
} /// <summary>
/// 对内容进行编码
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string UrlEncode(string str)
{
StringBuilder sb = new StringBuilder();
byte[] byStr = System.Text.Encoding.GetEncoding("gbk").GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
for (int i = 0; i < byStr.Length; i++)
{
sb.Append(@"%" + Convert.ToString(byStr[i], 16));
} return (sb.ToString());
}
/// <summary>
///
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
private static string ReadStreamFromResponse(WebResponse response, string content)
{
Stream responseStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(responseStream))
{
string strContent = sr.ReadToEnd();
return strContent;
}
} delegate string SynchOperation(string value);
/// <summary>
///
/// </summary>
/// <param name="callback"></param>
/// <param name="value"></param>
void BeginTheSynchronousOperation(AsyncCallback callback, string value)
{
SynchOperation op = new SynchOperation(SynchronousOperation);
op.BeginInvoke(value, callback, op);
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
string SynchronousOperation(string value)
{ string str = "geovindu";
Thread.Sleep(10000);
str = str + value;
return str;
}
/// <summary>
///
/// </summary>
/// <param name="result"></param>
void CallbackOperation(IAsyncResult result)
{
// get your delegate
var ar = result.AsyncState as SynchOperation;
// end invoke and get value
var returned = ar.EndInvoke(result);
Response.Write(returned); }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
BeginTheSynchronousOperation(CallbackOperation, this.TextBox1.Text.Trim());
var task = MakeAsyncRequest("application/x-www-form-urlencoded", "geovindu", "1388888888");
Response.Write(string.Format("Got response of {0}", task.Result)); //返回成功
}
第二种方法: 用HttpClient 更省代码 .net 4.6
/// <summary>
/// 发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{ Response.Write(isFail(sendMessage("138888888", "【六福珠宝】兴高高兴,天下为公", "geovindu"))); } /// <summary>
/// 发送信息
/// geovindu 涂聚文
/// </summary>
/// <param name="mobile"></param>
/// <param name="contenttxt"></param>
/// <param name="user"></param>
/// <returns></returns>
private string sendMessage(string mobile, string contenttxt, string user)
{
string result = string.Empty; Uri u = new Uri("http://www.dusystem.com/smsSend.do");
string pwd = "geovindu";//
string msg = UrlEncodeNew(contenttxt);
var payload = string.Format("username={0}&password={1}&mobile={2}&content={3}", "geovindu", pwd, mobile, msg);
HttpContent c = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
var t = Task.Run(() => PostURI(u, c));
t.Wait();
result=t.Result;
return result;
}
/// <summary>
/// 涂聚文 Geovin Du
///
/// </summary>
/// <param name="u"></param>
/// <param name="c"></param>
/// <returns></returns>
static async Task<string> PostURI(Uri u, HttpContent c)
{
var response = string.Empty;
using (var client = new HttpClient())
{
//string url = "http://myserver/method";
//string content = "param1=1¶m2=2";
//HttpClientHandler handler = new HttpClientHandler();
//HttpClient httpClient = new HttpClient(handler);
//HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, u);
//HttpResponseMessage response = await httpClient.SendAsync(request, content); HttpResponseMessage result = await client.PostAsync(u, c);
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
Task<string> t = result.Content.ReadAsStringAsync();
response = t.Result;
}
}
return response;
} private bool isFail(string i)
{
bool ok = false;
if (double.Parse(i) > 0)
{
ok = true;
}
return ok;
}
Csharp:HttpWebRequest or HttpClient的更多相关文章
- 在 IIS 6 和 IIS 7中配置Https,设置WCF同时支持HTTP和HTPPS,以及使用HttpWebRequest和HttpClient调用HttpS
IIS 7 ,给IIS添加CA证书以支持https IIS 6 架设证书服务器 及 让IIS启用HTTPS服务 WCF IIS 7中配置HTTPS C#利用HttpWebRequest进行post请求 ...
- webrequest HttpWebRequest webclient/HttpClient
webrequest(abstract类,不可直接用) <--- (继承)---- HttpWebRequest(更好的控制请求) <--- (继承)---- webclient (简单快 ...
- csharp: HttpWebRequest and HttpWebResponse
http://stackoverflow.com/questions/4015324/http-request-with-post Response.Charset = "GBK" ...
- WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择
NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...
- WebClient vs HttpClient vs HttpWebRequest
转载:http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/ Just when I was startin ...
- 如何选择 WebClient,HttpClient,HttpWebRequest
当我们在用 .NET 调用 RestAPI 时通常有三种选择,分别为:WebClient, HttpWebRequest,HttpClient,这篇文章我们将会讨论如何使用这三种方式去调用 RestA ...
- CSharp 相关知识点小结
1.JS获取iframe下面的内容document.getElementById('IFRAME1').contentDocument; 2.dialog 弹出层,定位:postion:'bottom ...
- C# HttpClient设置cookies的两种办法
前言:最近公司使用HttpClient对象在发送请求,抛弃了之前的HttpWebRequest,使用httpClient有个好处:就是可以只使用一个HttpClient的实例,去完成发送所有的请求数据 ...
- 【初码干货】关于.NET玩爬虫这些事
这几天在微信群里又聊到.NET可以救中国但是案例太少不深的问题,我说.NET玩爬虫简直就是宇宙第一,于是大神朱永光说,你为何不来写一篇总结一下? 那么今天就全面的来总结一下,在.NET生态下,如何玩爬 ...
随机推荐
- Netty网络框架
Netty网络框架 Netty是一个异步的基于事件驱动的网络框架. 为什么要使用Netty而不直接使用JAVA中的NIO 1.Netty支持三种IO模型同时支持三种Reactor模式. 2.Netty ...
- 分发系统介绍、expect脚本远程登录、expect脚本远程执行命令、expect脚本传递参数
7月19日任务 20.27 分发系统介绍20.28 expect脚本远程登录20.29 expect脚本远程执行命令20.30 expect脚本传递参数 20.27 分发系统介绍 公司业务逐渐扩大时, ...
- wpa_supplicant的移植
解压,进入,使用默认配置文件 cd wpa_supplicant-2.6 cp defconfig .config 修改.config文件,修改部分,根据自己的需要进行这部分的配置 #指定libnl的 ...
- 《Windows内核安全与驱动开发》 4.4 线程与事件
<Windows内核安全与驱动开发>阅读笔记 -- 索引目录 <Windows内核安全与驱动开发> 4.4 线程与事件 一.开辟一个线程,参数为(打印内容+打印次数),利用线程 ...
- Delphi7 - Server Monitor开发并实现指定端口定时刷新、重启和邮件提醒等功能
项目背景 近期,总经办邮件反馈考勤数据频繁丢失,请IT排查其根本原因,并提供整改措施. 措不及防,这个项目当初并不是IT主导的,是设备部采购,然后协同软件供应商直接安装.部署和调试的,IT只是提供几个 ...
- 使用python实现http服务器
主要使用python实现了一个http服务器.http服务器实现了用户的注册和登录的简单功能,当然还可以继续扩展. 数据的存储使用的是文件,有兴趣的话可以使用数据库进行存储.当然根据个人兴趣而定. 本 ...
- 洛谷 题解 P5595 【【XR-4】歌唱比赛】
本蒟蒻又双叒叕被爆踩了. 考试时一遍过 其实这题还是很简单的,难度不会大于普及组T1. CSP 2019 RP++ 看开始看到题目,觉得特别长,不想看... 我来和你们分析分析题目,你们就都可以秒了. ...
- 编码规范(c#)
万丈高楼平地起,好的编码风格能让别人撸起来更带劲,反之则想吐槽这是哪个傻X写的,这都是些什么乱七八糟的玩意? 然后看后面的注释发现是自己以前写的,那场面一度很尴尬.... 规约不是规则,不是一定要这样 ...
- ios高效开发-正确的使用枚举(Enum)
前言 Enum,也就是枚举,从C语言开始就有了,C++.Java.Objective-C.Swift这些语言,当然都有对应的枚举类型,功能可能有多有少,但是最核心的还是一个—规范的定义代码中的状态.选 ...
- DOM中操作结点的属性_操作元素结点的样式
有俩种方式操作结点的属性. 首先我们需要先获取所要操作的结点元素: var uname=document.getElementById("uname"); var gan=unam ...