码迷,mamicode.com
首页 > Windows程序 > 详细

.NET / C# HTTP中的GET请求

时间:2019-10-23 18:23:45      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:form   读取   span   net   turn   col   read   ret   data   

        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;

.NET / C# HTTP中的GET请求

标签:form   读取   span   net   turn   col   read   ret   data   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!