1 | |
1.WebRequest方式
Post:
private void button1_Click(object sender, EventArgs e)
{
string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
}
public static string HttpPost(string url, string body)
{
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
Get:
private void button1_Click(object sender, EventArgs e)
{
string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京");
}
public static string HttpGet(string url)
{
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
2.HttpClient 方式
Post:
private async void button2_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
//由HttpClient发出Delete Method
HttpResponseMessage response = await client.DeleteAsync("http://localhost:41558/api/Demo"+"/1");
if (response.IsSuccessStatusCode)
MessageBox.Show("成功");
}
private async void button3_Click(object sender, EventArgs e)
{
//创建一个处理序列化的DataContractJsonSerializer
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
MemoryStream ms = new MemoryStream();
//将资料写入MemoryStream
serializer.WriteObject(ms, new People() { Id = 1, Name = "Hello ni" });
//一定要在这设定Position
ms.Position = 0;
HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
//由HttpClient发出Put Method
HttpResponseMessage response = await client.PutAsync("http://localhost:41558/api/Demo"+ "/1", content);
if (response.IsSuccessStatusCode)
MessageBox.Show("成功");
}
Get:
using (WebClient client = new WebClient())
{
client.Headers["Type"] = "GET";
client.Headers["Accept"] = "application/json";
client.Encoding = Encoding.UTF8;
client.DownloadStringCompleted += (senderobj, es) =>
{
var obj = es.Result;
};
client.DownloadStringAsync("http://localhost:41558/api/Demo");
}
WebAPI接收处理(方法没用参数,不喜欢用参数,反而觉得不好控制)
public class DefaultController : ApiController
{
// GET api/values/5
public List<Site> Get()
{
string Name = System.Web.HttpContext.Current.Request["Name"].ToString();
var sites = new List<Site>();
sites.Add(new Site { SiteId = 1, Title = "test", Uri = "www.cnblogs.cc" });
sites.Add(new Site { SiteId = 2, Title = "博客园首页", Uri = "www.cnblogs.com" });
sites.Add(new Site { SiteId = 3, Title = "博问", Uri = "q.cnblogs.com" });
sites.Add(new Site { SiteId = 4, Title = "新闻", Uri = "news.cnblogs.com" });
sites.Add(new Site { SiteId = 5, Title = "招聘", Uri = "job.cnblogs.com" });
var result = (from Site site in sites where site.SiteId > 0 select site).Take(10).ToList();
return result;
}
// POST api/values
public List<Site> Post()
{
System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
string Name= System.Text.Encoding.UTF8.GetString(b);
var sites = new List<Site>();
sites.Add(new Site { SiteId = 1, Title = "test", Uri = "www.cnblogs.cc" });
sites.Add(new Site { SiteId = 2, Title = "博客园首页2", Uri = "www.cnblogs.com" });
sites.Add(new Site { SiteId = 3, Title = "博问", Uri = "q.cnblogs.com" });
sites.Add(new Site { SiteId = 4, Title = "新闻", Uri = "news.cnblogs.com" });
sites.Add(new Site { SiteId = 5, Title = "招聘", Uri = "job.cnblogs.com" });
var result = (from Site site in sites where site.SiteId > 0 select site).Take(10).ToList();
return result;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2012-05-25 Windows 7禁ping解决方法
2009-05-25 获取iframe外页面url(小技巧)
2007-05-25 C#中实例一个自定义类的数组的做法