1.编写url地址
string url="http://192.168";
2.创建http请求对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
3.指定请求方法
request.Method="POST"/"GET"...
4.准备参数对象,将其转换为JSON格式后写入request请求中
var routingInfo = new { ID = "1234", Name="sa" }; JsonSerializerSettings jsonSettings = new JsonSerializerSettings(); jsonSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ"; var json = JsonConvert.SerializeObject(routingInfo, jsonSettings); byte[] data = Encoding.UTF8.GetBytes(json); request.GetRequestStream().Write(data, 0, data.Length);
5.添加头部信息
request.Headers.Add("header1", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")); request.Headers.Add("header2", "123");
6.发送请求,并处理数据
try { //发送请求 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //提取Body信息 string respJson = ExtractResponseBody(resp); //对数据进行处理 txt_result.Text = respJson; } catch (Exception ex) { //捕捉错误信息 txt_result.Text = ex.Message.ToString(); }
标签:jsonSettings,调用,请求,C#,resp,request,接口,url,data From: https://www.cnblogs.com/budongdong/p/16829334.html