当前位置:首页 > Windows程序 > 正文

.NET / C# HTTP中的GET请求

2024-03-31 Windows程序

public string GET2(string URL) { HttpWebRequest Request = (HttpWebRequest)WebRequest.CreateHttp(URL);//创建httpWebRequest对象 //设置属性,初始化HttpWebRequest对象 Request.Method = "GET"; Request.Timeout = 30000; Request.ContentType = "application/x-www-form-urlencoded"; // 读取服务器的返回信息 HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //将信息流转换为字符串 StreamReader Reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8); var as1 = Reader.ReadToEnd();//以字符串形式返回信息流 Response.Close();//关闭响应释放资源 Reader.Close();//关闭流,释放资源 return as1; } public string POST2(string URL,string DataJSON) { HttpWebRequest Request = (HttpWebRequest)WebRequest.CreateHttp(URL);//创建httpWebRequest对象 //设置属性,初始化HttpWebRequest对象 Request.Method = "POST"; Request.Timeout = 30000; Request.ContentType = "application/x-www-form-urlencoded"; // 附加要POST给服务器的数据到HttpWebRequest对象 json是键 DataJSON是值 Stream reqStream = Request.GetRequestStream(); byte[] byteArray = Encoding.UTF8.GetBytes("json=" + DataJSON);//("json=" + DataJSON+"&name=‘123456‘")传多值 reqStream.Write(byteArray, 0, byteArray.Length); reqStream.Close(); // 读取服务器的返回信息 HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //将信息流转换为字符串 StreamReader Reader = new StreamReader(Response.GetResponseStream(), Encoding.ASCII); var as1 = Reader.ReadToEnd();//以字符串形式返回信息流 Response.Close(); Reader.Close(); return as1; }

需要引入using System.IO;using System.Net;

标签:

原文地址:https://www.cnblogs.com/xianyv/p/11727549.html

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/8780.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494584访问次数
  • 建站天数
  • 友情链接