Get方式:
static void Main(string[] args) { string l_strUrl = "http://www.baidu.com"; // 请求URL1 HttpWebRequest l_httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(l_strUrl); // 创建连接 l_httpWebRequest.Method = "get"; // 请求方式 l_httpWebRequest.Timeout = 10000; // 超时时间 var request = l_httpWebRequest.GetResponse(); // 获取响应 StreamReader l_streamR = new StreamReader(request.GetResponseStream(), Encoding.UTF8); // 转换为流 string l_strXml = l_streamR.ReadToEnd(); // 获取流中的数据 l_streamR.Close(); // 关闭 File.WriteAllText("D:/Code/Demo/Demo/upload/index.html", l_strXml); // 将获取到的信息写入文本 // //Console.Write(l_strXml); Console.ReadKey(); }
Post方式:
SeDemo.cs: using SeDemo.Entitys; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http; namespace SeDemo.Controllers { public class DefaultController : ApiController { [HttpGet] public string Get() { HttpWebRequest l_httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:61614/api/Index"); l_httpWebRequest.Method = "POST"; l_httpWebRequest.ContentType = "application/json"; l_httpWebRequest.Timeout = 100000; // 构造相应数据 string l_data = "{id:1,name:‘namejr‘,age:12}"; // 值得注意的是,这里的构造数据和前段的一样 byte[] l_byteData = Encoding.UTF8.GetBytes(l_data.ToString()); l_httpWebRequest.ContentLength = l_byteData.Length; l_httpWebRequest.GetRequestStream().Write(l_byteData, 0, l_byteData.Length); //Stream l_stream = l_httpWebRequest.GetRequestStream(); //l_stream.Write(l_byteData, 0, l_byteData.Length); //l_stream.Close(); // 获取响应并解析 var l_response = l_httpWebRequest.GetResponse(); StreamReader l_sr = new StreamReader(l_response.GetResponseStream(), Encoding.UTF8); string l_retXml = l_sr.ReadToEnd(); l_sr.Close(); return l_retXml; } } } ============================================== using SeDemo.Entitys; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SeDemo.Controllers { public class IndexController : ApiController { [HttpGet] public string Get() { return "Hello world!!!"; } [HttpPost] public string Post([FromBody]MessageInfo a_entitys) { string l_strTemp = ""; if(a_entitys!=null&&!string.IsNullOrEmpty(a_entitys.id.ToString())) { l_strTemp = string.Format("{0}=>{1}=>{2}", a_entitys.id, a_entitys.name, a_entitys.age); } else { l_strTemp = string.Format("传不上来哟!!!"); } return l_strTemp; } } }
原文地址:https://www.cnblogs.com/namejr/p/11697016.html
时间: 2024-10-22 08:39:57