webclient 和httpclient 应用

//webclient应用
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; }

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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();
 
  }

  

 

 
复制代码

//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()获取返回值

转载于:https://www.cnblogs.com/shiyh/p/9273619.html

WebClient 是一种网络工具类,在 Javajava.net 包中提供了一个用于访问远程资源的类。它主要用于通过 HTTP 协议获取 URL 对象所指向的数据流,并将其转换为各种 Java 类型的对象,如 String、byte[] 等。WebClient 支持多种请求方法(GET, POST, PUT, DELETE等),并允许用户自定义HTTP头信息,适用于简单的网络请求场景。 WebClient 的主要优点包括: 1. **易于使用**:相比于传统的 URLConnection 或 HttpURLConnection,WebClient 提供了更简洁的 API 来发送 HTTP 请求和处理响应。 2. **支持自动解码**:WebClient 可以自动处理返回数据的不同编码,使得开发者不需要过多关注字符集问题。 3. **错误处理**:内置了对常见 HTTP 错误状态的处理机制,例如超时、连接失败等,提高了程序的健壮性和用户体验。 4. **可定制化**:允许开发者自定义客户端的行为,比如设置代理服务器、认证信息、请求超时时间等。 5. **异步操作**:通过回调函数或者 Future 接口,可以让程序在等待数据返回的同时继续执行其他任务,提高系统效率。 WebClient 主要应用场景包括但不限于: - **网页抓取**:从网站上抓取数据,构建数据仓库或进行数据分析。 - **API 调用**:向第三方服务发送请求获取数据,例如天气预报服务、地图服务等。 - **文件下载**:将远程文件下载到本地存储。 虽然 WebClient 是一个功能全面的类,但它也有一些限制,尤其是在处理复杂请求或需要高灵活性的时候,可能不如一些专门的库(如 Apache HttpClient)那么强大。因此,在实际项目中选择合适的网络工具类通常取决于项目的具体需求和技术栈的偏好。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值