asp.net后台发送HTTP请求
2017-03-10 01:09 NO.27 阅读(10760) 评论(0) 编辑 收藏 举报一、文件流方式(转自:http://blog.csdn.net/u011511086/article/details/53216330)
/// 发送请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="sendData">参数格式 “name=王武&pass=123456”</param> /// <returns></returns> public static string RequestWebAPI(string url, string sendData) { string backMsg = ""; try { System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url); httpRquest.Method = "POST"; //这行代码很关键,不设置ContentType将导致后台参数获取不到值 httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData); //httpRquest.ContentLength = dataArray.Length; System.IO.Stream requestStream = null; if (string.IsNullOrWhiteSpace(sendData) == false) { requestStream = httpRquest.GetRequestStream(); requestStream.Write(dataArray, 0, dataArray.Length); requestStream.Close(); } System.Net.WebResponse response = httpRquest.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8); backMsg = reader.ReadToEnd(); reader.Close(); reader.Dispose(); requestStream.Dispose(); responseStream.Close(); responseStream.Dispose(); } catch (Exception) { throw; } return backMsg; }
二、HttpClient方式(转自:http://blog.csdn.net/qianmenfei/article/details/37974767)
1、通用http类
using System; using System.Globalization; using System.Net; using System.Text; namespace Test { public class HttpCommon { /// <summary> /// Http同步Get同步请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="encode">编码(默认UTF8)</param> /// <returns></returns> public static string HttpGet(string url, Encoding encode = null) { string result; try { var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null) webClient.Encoding = encode; result = webClient.DownloadString(url); } catch (Exception ex) { result = ex.Message; } return result; } /// <summary> /// Http同步Get异步请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="callBackDownStringCompleted">回调事件</param> /// <param name="encode">编码(默认UTF8)</param> public static void HttpGetAsync(string url, DownloadStringCompletedEventHandler callBackDownStringCompleted = null, Encoding encode = null) { var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null) webClient.Encoding = encode; if (callBackDownStringCompleted != null) webClient.DownloadStringCompleted += callBackDownStringCompleted; webClient.DownloadStringAsync(new Uri(url)); } /// <summary> /// Http同步Post同步请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="postStr">请求Url数据</param> /// <param name="encode">编码(默认UTF8)</param> /// <returns></returns> public static string HttpPost(string url, string postStr = "", Encoding encode = null) { string result; try { var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null) webClient.Encoding = encode; var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); var readData = webClient.UploadData(url, "POST", sendData); result = Encoding.GetEncoding("GB2312").GetString(readData); } catch (Exception ex) { result = ex.Message; } return result; } /// <summary> /// Http同步Post异步请求 /// </summary> /// <param name="url">Url地址</param> /// <param name="postStr">请求Url数据</param> /// <param name="callBackUploadDataCompleted">回调事件</param> /// <param name="encode"></param> public static void HttpPostAsync(string url, string postStr = "", UploadDataCompletedEventHandler callBackUploadDataCompleted = null, Encoding encode = null) { var webClient = new WebClient { Encoding = Encoding.UTF8 }; if (encode != null) webClient.Encoding = encode; var sendData = Encoding.GetEncoding("GB2312").GetBytes(postStr); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); webClient.Headers.Add("ContentLength", sendData.Length.ToString(CultureInfo.InvariantCulture)); if (callBackUploadDataCompleted != null) webClient.UploadDataCompleted += callBackUploadDataCompleted; webClient.UploadDataAsync(new Uri(url), "POST", sendData); } } }
2、调用类
using System; using System.Net; using System.Text; using System.Web.UI; namespace Test { public partial class WebForm3 : Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(HttpCommon.HttpGet("http://localhost:14954/WebForm4.aspx")); //Get同步 HttpCommon.HttpGetAsync("http://localhost:14954/WebForm4.aspx"); //Get异步 HttpCommon.HttpGetAsync("http://localhost:14954/WebForm4.aspx", DownStringCompleted); //Get异步回调 Response.Write(HttpCommon.HttpPost("http://localhost:14954/WebForm4.aspx", "post=POST")); //Post同步 HttpCommon.HttpPostAsync("http://localhost:14954/WebForm4.aspx", "post=POST"); //Post异步 HttpCommon.HttpPostAsync("http://localhost:14954/WebForm4.aspx", "post=POST", UploadDataCompleted); //Post异步回调 } private void DownStringCompleted(object sender, DownloadStringCompletedEventArgs e) { Response.Write(e.Result); } private void UploadDataCompleted(object sender, UploadDataCompletedEventArgs e) { Response.Write(Encoding.GetEncoding("GB2312").GetString(e.Result)); } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 个人数据保全计划:从印象笔记迁移到joplin
· Vue3.5常用特性整理
· 重拾 SSH:从基础到安全加固
· 为什么UNIX使用init进程启动其他进程?