Http请求方法封装
-
POST请求
public static string HttpPost(string url, string data) { string address = url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); request.Method = "POST"; request.ContentType = "application/json"; string strContent = data; //json字符串 using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream())) { dataStream.Write(strContent); dataStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); string retString = reader.ReadToEnd(); //解析josn //JObject jo = JObject.Parse(retString); return retString; }
-
GET请求
//[WebMethod] public static string HttpGet(string url) { //预备请求的资源 HttpWebRequest request = null; HttpWebResponse response = null; StreamReader reader = null; string content = string.Empty; //实例化一个http请求 request = (HttpWebRequest)WebRequest.Create(url); //设置请求头 请求方式method=get request.Method = "GET"; //使request。getResponse()返回的一个响应对象 response = (HttpWebResponse)request.GetResponse(); //reader 读取响应流 using (reader = new StreamReader(response.GetResponseStream())) { //意思是从头读到尾,全部读完 content = reader.ReadToEnd(); } return content; }
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/17121870.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了