平时工作中长期需要用到通过HTTP调用API进行数据获取以及文件上传下载(C#,JAVA...都会用到)。这里获取的是包括网页的所有信息。如果单纯需要某些数据内容。可以自己构造函数甄别抠除出来!一般的做法是根据源码的格式,用正则来过滤出你需要的内容部分。

  C#中的调用:

    方式一:webclient和httpclient

    方式二:WebRequest和webresponse

    方式三:通过js 直接访问api接口,页面通过jquery调用

    方式四:WebBrowser

1.webclient和httpclient

  实例①

#region webclient应用
        #region Controllers
        MyImageServerEntities db = new MyImageServerEntities();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult FileUpload()
        {
            HttpPostedFileBase file = Request.Files["fileUp"];
            string fileName = Path.GetFileName(file.FileName);
            string fileExt = Path.GetExtension(fileName);
            if (fileExt == ".jpg")
            {
                var list = db.ImageServerInfo.Where<ImageServerInfo>(u => u.FlgUsable == true).ToList();//找出可用的图片服务器.
                int count = list.Count();
                Random random = new Random();
                int r = random.Next();
                int i = r % count;
                string serverUrl = list[i].ServerUrl;
                int serverId = list[i].ServerId;
                string url = "http://" + serverUrl + "/FileUp.ashx?serverId=" + serverId + "&fileExt=" + fileExt;
                WebClient webClient = new WebClient();
                webClient.UploadData(url, StreamToBytes(file.InputStream));

            }
            return Content("ok");

        }
        public ActionResult ShowImage()
        {
            var list = db.ImageServerInfo.Where<ImageServerInfo>(c => c.FlgUsable == true).ToList();
            ViewData["imageServerList"] = list;
            return View();
        }
        private byte[] StreamToBytes(Stream stream)
        {
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return buffer;
        }
        #endregion

        #region Model
        context.Response.ContentType = "text/plain"; 
        int serverId = int.Parse(context.Request["serverId"]);
        string fileExt = context.Request["fileExt"];
        string dir = "/ImagePath/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
        Directory.CreateDirectory(Path.GetDirectoryName(context.Request.MapPath(dir))); 
        string newfileName = Guid.NewGuid().ToString();
        string fullDir = dir + newfileName + fileExt;
        using (FileStream fileStream = File.Open(context.Request.MapPath(fullDir), FileMode.OpenOrCreate)) 
        { 
            context.Request.InputStream.CopyTo(fileStream);     
            MyImageServerEntities db = new MyImageServerEntities();
            ImageInfo imageInfo = new ImageInfo();
            imageInfo.ImageName = fullDir;     
            imageInfo.ImageServerId = serverId;     
            db.ImageInfo.Add(imageInfo);    
            db.SaveChanges(); 
         }
#endregion
#endregion

#region httpclient
创建并初始化对象:
    client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

读集合:
    HttpResponseMessage response = client.GetAsync(url).Result;
var userList = response.Content.ReadAsAsync<IEnumerable<数据类型>>().Result;

根据编号读对象
    HttpResponseMessage response1 = client.GetAsync(url).Result;
    var userInfo = response1.Content.ReadAsAsync<数据类型>().Result;

增加:
    HttpResponseMessage response = client.PostAsJsonAsync("api/userinfo", userInfo).Result;
使用response.IsSuccessStatusCode判断是否成功
使用response.Content.ToString()获取返回值

修改:
     HttpResponseMessage response = client.PutAsJsonAsync("api/userinfo/" + userInfo.UserId, userInfo).Result;
使用response.IsSuccessStatusCode判断是否成功
使用response.Content.ToString()获取返回值

删除:
    HttpResponseMessage response = client.DeleteAsync("api/userinfo/" + uid).Result;
使用response.IsSuccessStatusCode判断是否成功
使用response.Content.ToString()获取返回值
        #endregion
View Code

相关文章:

  • 2021-06-20
  • 2021-10-29
  • 2021-10-28
  • 2021-06-28
猜你喜欢
  • 2021-12-26
  • 2022-12-23
  • 2022-03-01
  • 2022-12-23
  • 2021-12-12
相关资源
相似解决方案