/// <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&param2=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的更多相关文章

  1. 在 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请求 ...

  2. webrequest HttpWebRequest webclient/HttpClient

    webrequest(abstract类,不可直接用) <--- (继承)---- HttpWebRequest(更好的控制请求) <--- (继承)---- webclient (简单快 ...

  3. csharp: HttpWebRequest and HttpWebResponse

    http://stackoverflow.com/questions/4015324/http-request-with-post Response.Charset = "GBK" ...

  4. WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择

    NETCore提供了三种不同类型用于生产的REST API: HttpWebRequest;WebClient;HttpClient,开源社区创建了另一个名为RestSharp的库.如此多的http库 ...

  5. WebClient vs HttpClient vs HttpWebRequest

    转载:http://www.diogonunes.com/blog/webclient-vs-httpclient-vs-httpwebrequest/ Just when I was startin ...

  6. 如何选择 WebClient,HttpClient,HttpWebRequest

    当我们在用 .NET 调用 RestAPI 时通常有三种选择,分别为:WebClient, HttpWebRequest,HttpClient,这篇文章我们将会讨论如何使用这三种方式去调用 RestA ...

  7. CSharp 相关知识点小结

    1.JS获取iframe下面的内容document.getElementById('IFRAME1').contentDocument; 2.dialog 弹出层,定位:postion:'bottom ...

  8. C# HttpClient设置cookies的两种办法

    前言:最近公司使用HttpClient对象在发送请求,抛弃了之前的HttpWebRequest,使用httpClient有个好处:就是可以只使用一个HttpClient的实例,去完成发送所有的请求数据 ...

  9. 【初码干货】关于.NET玩爬虫这些事

    这几天在微信群里又聊到.NET可以救中国但是案例太少不深的问题,我说.NET玩爬虫简直就是宇宙第一,于是大神朱永光说,你为何不来写一篇总结一下? 那么今天就全面的来总结一下,在.NET生态下,如何玩爬 ...

随机推荐

  1. 69道Spring面试题及答案

    目录 Spring 概述 依赖注入 Spring beans Spring注解 Spring数据访问 Spring面向切面编程(AOP) Spring MVC Spring 概述 1. 什么是spri ...

  2. Django简介以及MVC模式

    一.简介 Django,是当前Python世界里最负盛名且成熟的网络框架.最初用来制作在线新闻的Web站点. Django是一个基于python的web重量级框架 重指的是为发开者考虑的多 采用了MV ...

  3. 小白都会用的免配置 Aria2 图形界面版免费开源下载软件PDM

    如今的迅雷真的越发让人失望,好好的下载软件变成了广告浏览器,最近又关停了“远程下载”功能,就算花钱加入会员,很多资源现在也不允许下载了,鸡肋的很. 然而除了 IDM.Folx.qBitorrent 等 ...

  4. .NET进阶篇06-async异步、thread多线程4

    知识需要不断积累.总结和沉淀,思考和写作是成长的催化剂 梯子 一.锁1.lock2.Interlocked3.Monitor4.SpinLock5.Mutex6.Semaphore7.Events1. ...

  5. 如何使用Git命令克隆仓库代码

    今天我的电脑装了新系统,刚装了Git到电脑上,突然有一个大胆的想法,以后不适用可视化工具了. 要逐步锻炼我的命令的操作能力,不能太依赖可视化工具. 今天先记录一下如何使用git命令克隆仓库代码 git ...

  6. 超好用的自带火焰图的 Java 性能分析工具 Async-profiler 了解一下

    如果你经常遇到 Java 线上性能问题束手无策,看着线上服务 CPU 飙升一筹莫展,发现内存不断泄露满脸茫然.别慌,这里有一款低开销.自带火焰图.让你大呼好用的 Java 性能分析工具 - async ...

  7. AI:为你写诗,为你做不可能的事

    最近,一档全程高能的神仙节目,高调地杀入了我们的视野: 没错,就是撒贝宁主持,董卿.康辉等央视名嘴作为评审嘉宾,同时集齐央视"三大名嘴"同台的央视<主持人大赛>,这够不 ...

  8. Forrester:华为云容器是容器混合云最佳选择

    近日,国际权威咨询机构Forrester发布<The Forrester New WaveTM: Public Cloud Enterprise Container Platforms, Q3 ...

  9. Python一秒搭建ftp服务器,帮助你在局域网共享文件

    "老板 来碗面" "要啥面?" "内牛满面.." 最近项目上的事情弄得人心累,本来是帮着兄弟项目写套入口代码,搞着搞着就被拉着入坑了.搞开发 ...

  10. 你知道,HTTPS用的是对称加密还是非对称加密?

    1.引言 随着互联网安全意识的普遍提高,对安全要求稍高的应用中,HTTPS的使用是很常见的,甚至在1年前,苹果公司就将使用HTTPS作为APP上架苹果应用市场的先决条件之一(详见<苹果即将强制实 ...