WebClient和HttpClient, 以及webapi上传图片

httppost请求.

applicationkey/x-www-form-urlencoded

请求: Email=321a&Name=kkfew

webapi里面, 如果用实体, 能接受到. 因为这是一个属性一个属性去匹配的原因

application/json

请求:{Email:321a  ,  Name:kkfew}

如果接收参数为dynamic, 则没有问题.
因为直接把json对象转化成dynamic对象了

using (WebClient webclient = new WebClient())
            {

                string apiurl = "http://192.168.1.225:9090/api/v3productsapi/GetStatisticInfo";

                webclient.Encoding = UTF8Encoding.UTF8;

                string auth_key = string.Format("{0}:{1}:{2}", ts.TotalSeconds, randomStr, token);
                webclient.Headers.Add("Custom-Auth-Key", auth_key);

                Console.Write(webclient.DownloadString(apiurl));
            }

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://192.168.1.225:9090/");
                client.DefaultRequestHeaders.Add("aa", "11");
                var result = client.GetStringAsync("/api/v3productsapi/GetStatisticInfo").Result;
                Console.WriteLine(result);
            }

post

System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

            using (var client = new HttpClient())//httpclient的post方式, 需要被实体接收..
            {
                string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform2";
                //3个枚举, stringContent,ByteArrayContent,和FormUrlContent, 一般的post用StringContent就可以了
                using (var content = new StringContent(
                    "Email=321a&Name=kkfew", Encoding.UTF8, "application/x-www-form-urlencoded"))
                {
                    content.Headers.Add("aa", "11"); //默认会使用
                    var result = client.PostAsync(apiurl, content).Result;
                    Console.WriteLine(result);
                }
            }
            using (var client = new HttpClient())
            {
                string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform";
                using (var content = new StringContent(json.Serialize(new { Email = "1", Name = "2" })))
                {
                    content.Headers.Add("aa", "11");
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var result = client.PostAsync(apiurl, content).Result;
                    Console.WriteLine(result);
                }
            }
            using (WebClient webclient = new WebClient())
            {

                string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform2";

                webclient.Encoding = UTF8Encoding.UTF8;
                webclient.Headers.Add("Custom-Auth-Key", "11");
                webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//x-www-form-urlencoded
                //如果webapi的接收参数对象是dynamic, 则请求的头是json, 如果是用实体接收, 那么则是上面这个

                var re = webclient.UploadData(apiurl,
                   System.Text.Encoding.UTF8.GetBytes("Email=321a&Name=kkfew"));

                Console.Write(System.Text.Encoding.UTF8.GetString(re));
            }

            using (WebClient webclient = new WebClient())
            {

                string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform";

                webclient.Encoding = UTF8Encoding.UTF8;
                webclient.Headers.Add("Custom-Auth-Key", "11");
                webclient.Headers.Add("Content-Type", "application/json");//x-www-form-urlencoded
                //如果webapi的接收参数对象是dynamic, 则请求的头是json, 如果是用实体接收, 那么则是上面这个

                 var re = webclient.UploadData(apiurl,
                    System.Text.Encoding.UTF8.GetBytes(json.Serialize(new { email = "[email protected]", password = "111111" })));

                Console.Write(System.Text.Encoding.UTF8.GetString(re));
            }

上传图片

using (WebClient webclient = new WebClient())
            {

                string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/post";

                webclient.Encoding = UTF8Encoding.UTF8;
                string auth_key = string.Format("aa", "111");
                webclient.Headers.Add("Custom-Auth-Key", auth_key);

                byte[] b = webclient.UploadFile(apiurl, @"c:\2.jpg");

                Console.Write(System.Text.Encoding.UTF8.GetString(b));
            }

            using (var client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    client.BaseAddress = new Uri("http://192.168.1.225:9090/");
                    var fileContent = new ByteArrayContent(File.ReadAllBytes(@"c:\1.jpg"));
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "1.jpg"
                    };

                    content.Add(fileContent);
                    content.Headers.Add("aa", "ssssss");
                    var result = client.PostAsync("/api/V3ImageUploadApi/post", content).Result;
                    Console.WriteLine(result.Content.ReadAsStringAsync().Result);
                }
            }
[HttpPost]
        public HttpResponseMessage Post()
        {
            try
            {
                if (!IsValidateTokenPost)
                {
                    return TokenException();
                }

                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                var apiResult = new ApiResult();

                string root = HostingEnvironment.MapPath("~/content/images/uploaded/fromwechart");
                if (!System.IO.Directory.Exists(root))
                    System.IO.Directory.CreateDirectory(root);
                var provider = new MultipartFormDataStreamProvider(root);
                string OssFilename = "";

                //下面代码让异步变成同步, 因为要返回上传完图片之后新的图片绝对路径
                IEnumerable parts = null;
                Task.Factory
                    .StartNew(() =>
                    {
                        parts = Request.Content.ReadAsMultipartAsync(provider).Result.Contents;
                        foreach (MultipartFileData file in provider.FileData)
                        {
                            //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                            //Trace.WriteLine("Server file path: " + file.LocalFileName);
                            var fileName = file.Headers.ContentDisposition.FileName;
                            OssFilename = System.Guid.NewGuid() + "." + fileName.Split(‘.‘)[1];
                            using (FileStream fs = new FileStream(file.LocalFileName, FileMode.Open))
                            {
                                PutImageFileToOss(fs, "image/" + fileName.Split(‘.‘)[1], OssFilename);

                            }
                            if (File.Exists(file.LocalFileName))//上传完删除
                                    File.Delete(file.LocalFileName);
                        }
                    },
                    CancellationToken.None,
                    TaskCreationOptions.LongRunning, // guarantees separate thread
                    TaskScheduler.Default)
                    .Wait();

                string picUrl = "http://" + OssService.OssConfig.Domain + "/" + "content/sitefiles/" + _StoreContext.CurrentStore.SiteId + "/images/" + OssFilename;

                return Json(new ApiResult { StatusCode = StatusCode.成功, Info = new { filename = picUrl } });
            }
            catch (Exception ex)
            {
                return Json(ApiResult.InnerException(ex));
            }

        }
时间: 2024-12-04 06:38:42

WebClient和HttpClient, 以及webapi上传图片的相关文章

kindeditor扩展粘贴图片功能&修改图片上传路径并通过webapi上传图片到图片服务器

前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功能 kindeditor修改图片上传路径并通过webapi上传图片到图片服务器(支持分布式图片) 结果演示 1.扩展粘贴图片功能演示 2.修改图片上传路径演示: 我们的网站演示地址是:http://localhost:9393/ 我们的图片服务器地址是:http://localhost:9394/

WebApi上传图片 await关键字

await关键字对于方法执行的影响 将上一篇WebApi上传图片中代码修改(使用了await关键字)如下: [HttpPost] public async Task<string> Post() { if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Req

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.Fi

WebClient实现kindeditor跨域上传图片

尝试上传图片到一个单独的服务器,使用的是KindeEditor 4.1.10 kindeditor上传图片原理是: 上传按钮提交到iframe,生成1个form和1个iframe,form提交到(arget)iframeiframe的onload方法获取返回的值,然后调用配置回调方法afterUpload/afterError. 第一次尝试 页面A document.domain = "aaa.xx.com"; 图片服务器B document.domain = "bbb.xx

.Net Core WebApi上传图片的两种方式

我这边主要是为了上传图片,话不多说,上代码. 方式一:通过Form表单上传 后端: /// <summary> /// 上传图片,通过Form表单提交 /// </summary> /// <returns></returns> [Route("Upload/FormImg")] [HttpPost] public ActionResult UploadImg(List<IFormFile> files) { if (file

httpclient与webapi

System.Net.Http 是微软推出的最新的 HTTP 应用程序的编程接口, 微软称之为“现代化的 HTTP 编程接口”, 主要提供如下内容: 1. 用户通过 HTTP 使用现代化的 Web Service 的客户端组件: 2. 能够同时在客户端与服务端同时使用的 HTTP 组件(比如处理 HTTP 标头和消息), 为客户端和服务端提供一致的编程模型. 命名空间  System.Net.Http  以及  System.Net.Http.Headers  提供了如下内容: 1.  Http

HttpClient 调用WebAPI时,传参的三种方式

public void Post() { //方法一,传json参数 var d = new { username = " ", password = " ", grant_type = "password", appcode = " ", companyid = " ", version = "1.0", }; var data = JsonConvert.SerializeObjec

利用HttpClient调用WebApi

可以利用HttpClient来进行Web Api的调用.由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程, 所有HttpClient其实可以作为一般意义上发送HTTP请求的工具. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace

记录一个简单webapi 上传图片

图片转base64字符串,到接口后,再转回保存.代码里面是转成byte[]之后转的,也可以用base64字符串直接转图片. 只想记录一下简单的流程. 1,服务端 保存图片业务代码: public class UpLoadFile    {        public string UpLoad(string fileName,string filePath,byte[] fileData)        {            Bitmap map =BitmapFromBytes(fileD