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 = "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上传图片的更多相关文章
- 使用HttpClient调用WebAPI接口,含WebAPI端示例
API端: using log4net; using System; using System.Collections.Generic; using System.IO; using System.L ...
- WebApi上传图片 await关键字
await关键字对于方法执行的影响 将上一篇WebApi上传图片中代码修改(使用了await关键字)如下: [HttpPost] public async Task<string> Pos ...
- kindeditor修改图片上传路径-使用webapi上传图片到图片服务器
kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 在这里我着重介绍一些使用kindeditor修改图片上传路径并通过webapi上传图片到图片服务器的方案. 因为我使用的 ...
- kindeditor扩展粘贴图片功能&修改图片上传路径并通过webapi上传图片到图片服务器
前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...
- kindeditor扩展粘贴截图功能&修改图片上传路径并通过webapi上传图片到图片服务器
前言 kindeditor是一个非常好用的富文本编辑器,它的简单使用我就不再介绍了. 而kindeditor却对图片的处理不够理想. 本篇博文需要解决的问题有两个: kindeditor扩展粘贴图片功 ...
- HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 之间的区别
HttpRequest,WebRequest,HttpWebRequest,WebClient,HttpClient 今天我们来聊一下他们之间的关系与区别. HttpRequest 类 .NET Fr ...
- Asp.Net WebApi上传图片
webapi using System; using System.Collections; using System.Collections.Generic; using System.Diagno ...
- webrequest、httpwebrequest、webclient、HttpClient 四个类的区别
一.在 framework 开发环境下: webrequest.httpwebreques 都是基于Windows Api 进行包装, webclient 是基于webrequest 进行包装:(经 ...
- .Net5下WebRequest、WebClient、HttpClient是否还存在使用争议?
WebRequest.WebClient.HttpClient 是C#中常用的三个Http请求的类,时不时也会有人发表对这三个类使用场景的总结,本人是HttpClient 一把梭,也没太关注它们的内部 ...
随机推荐
- POJ 2513 Colored Sticks(欧拉回路,字典树,并查集)
题意:给定一些木棒,木棒两端都涂上颜色,求是否能将木棒首尾相接,连成一条直线,要求不同木棒相接的一边必须是相同颜色的. 无向图存在欧拉路的充要条件为: ① 图是连通的: ② 所有节 ...
- php类型转换以及类型转换的判别
部分摘自PHP: 类型 - Manual 相关链接 PHP 在变量定义中不需要(或不支持)明确的类型定义:变量类型是根据使用该变量的上下文所决定的.也就是说,如果把一个 string 值赋给变量 $v ...
- linux下查找某个目录下包含某个字符串的文件
有时候要找一些字符串,但是又不知道在哪个文件,只记得一些字符串 那么如何在linux下寻找包含某段文字的文件呢? 强大的find命令可以帮你完成不可能的任务. 比如我只记得我的程序里包含唯一的字符串“ ...
- C# 程序性能提升篇-1、装箱和拆箱,枚举的ToString浅析
前景提要: 编写程序时,也许你不经意间,就不知不觉的使程序代码,发生了装箱和拆箱,从而降低了效率,不要说就发生那么一次两次,如果说是程序中发生了循环.网络程序(不断请求处理的)等这些时候,减少装箱和拆 ...
- java 14 -1 正则表达式
正则表达式:符合一定规则的字符串. 1.判断QQ号码是否正确的案例: public class RegexDemo2 { public static void main(String[] args) ...
- Android事件分发机制完全解析,带你从源码的角度彻底理解
Android事件构成 在Android中,事件主要包括点按.长按.拖拽.滑动等,点按又包括单击和双击,另外还包括单指操作和多指操作.所有这些都构成了Android中的事件响应.总的来说,所有的事件都 ...
- js知识体系的梳理一
今天简单的总结了js的一些东西,梳理下整个体系,每一次的总结都会有不同的收获:js总结一一.[获取元素]: 1.通过ID: var oBtn=document.getElementById('btn1 ...
- javascript设置网页刷新或者重新加载后滚动条的位置不变
有个同事说再javascript中你可以做任何你想做的事情,当时觉得不以为然,今天遇到个问题,就是页面重新加载后总是回到页面的顶部,如果客户只想看到他想看到的部分是怎么变化的,这个体验就好了.原本想象 ...
- 解决ios下的微信打开的页面背景音乐无法自动播放
后面的项目发现,还有两个坑,需要注意下: ·本文的解决方案的核心是利用了 微信/易信 在ready的时候会有个 WeixinJSBridgeReady/YixinJSBridgeReady事件,通过监 ...
- ubuntu 查看软件包版本以及软件包的源码
aptitude show xxx sudo apt-cache show autoconf setattr, getattr, setattr http://ju.outofmemory.cn/e ...