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 = "123456@qq.com", 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));
} }

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

  1. 使用HttpClient调用WebAPI接口,含WebAPI端示例

    API端: using log4net; using System; using System.Collections.Generic; using System.IO; using System.L ...

  2. WebApi上传图片 await关键字

    await关键字对于方法执行的影响 将上一篇WebApi上传图片中代码修改(使用了await关键字)如下: [HttpPost] public async Task<string> Pos ...

  3. kindeditor修改图片上传路径-使用webapi上传图片到图片服务器

    kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...

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

    前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...

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

    前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...

  6. HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别

    HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别. HttpRequest 类 .NET Fr ...

  7. Asp.Net WebApi上传图片

    webapi using System; using System.Collections; using System.Collections.Generic; using System.Diagno ...

  8. webrequest、httpwebrequest、webclient、HttpClient 四个类的区别

    一.在 framework 开发环境下: webrequest.httpwebreques  都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...

  9. .Net5下WebRequest、WebClient、HttpClient是否还存在使用争议?

    WebRequest.WebClient.HttpClient 是C#中常用的三个Http请求的类,时不时也会有人发表对这三个类使用场景的总结,本人是HttpClient 一把梭,也没太关注它们的内部 ...

随机推荐

  1. css常见问题

    CSS: 1.垂直居中布局 (1)已知宽高 (2)未知宽高 https://segmentfault.com/q/1010000004073623 2.文字退格 text-indent: 4em; 3 ...

  2. 用shell脚本批量修改文件后缀名

    早上本想将一些照片上传到相册中,但是由于所有照片的扩展名都是JPG而不是小写的jpg,因此造成了“格式不正确”而不能上传照片.此刻就产生了这样一个问题:使用shell脚本如何批量将所有文件的扩展名JP ...

  3. 标准库shared_ptr智能指针的实现

    目前测试功能正常.若有不完善的地方在改进吧.时候不早了睡觉去,哎,翘课会被抓,不冒险了.晚安全世界O(∩_∩)O /****************************************** ...

  4. Mongodb--gridfs与分片实验

    1.放置一个大文件到gridfs,查看fs.chunks和fs.files的情况. Step1.开启一台mongod服务. ./mongod --dbpath dbs/master     登录mon ...

  5. 1.NopCommerce下载与安装

    NoCommerce是基于微软ASP.NET MVC + EntityFramework 技术开发的一套开源电子商城系统,其架构与设计非常精妙被誉为.NET商城的经典之作. 作为一个.NET程序爱好者 ...

  6. [编]IoT The Internet of Things (IoT) 物联网

    物联网是新一代信息技术的重要组成部分.其英文名称是“The Internet of things”.由此,顾名思义,“物联网就是物物相连的互联网”.这有两层意思:第一,物联网的核心和基础仍然是互联网, ...

  7. Linux上Eclipse项目右键菜单没有Maven

    在Centos 7上安装了eclipse以后,着实很兴奋.eclipse luna版本自带maven.但是用mvn eclipse:eclipse创建的java工程,在右键菜单居然没有Maven按钮, ...

  8. 【OpenCV】全景拼接

    从OpenCV3.0正式版开始,features2d中的一些接口,搬到附加库xfeatures2d中了,其中就有SIFT.SURF的特征检测方法,但是正常下载安装OpenCV并不包含附加库,因为附加库 ...

  9. HTML5性能优化

    HTML5性能优化 在看完这两章内容之后,我意犹未尽,于是乎从网上搜索关键字“Java Web高性能”,在IBM社区找到两篇不错的文章,而让人更意外的是我发现那两篇文章的内容跟<高性能HTML5 ...

  10. POJ 2823 Sliding Window 再探单调队列

    重新刷这个经典题,感觉跟以前不一样了,变得更加容易理解了,不讲解了,看代码.注意:要用C++提交,用G++会超时.. 代码: #include <iostream> #include &l ...