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 一把梭,也没太关注它们的内部 ...
随机推荐
- 深入JVM系列(三)之类加载、类加载器、双亲委派机制与常见问题
一.概述 定义:虚拟机把描述类的数据从Class文件加载到内存,并对数据进行校验.转换解析和初始化,最终形成可以被虚拟机直接使用的java类型.类加载和连接的过程都是在运行期间完成的. 二. 类的 ...
- NOIP2010普及组 三国游戏 -SilverN
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> usin ...
- hdu 5833 Zhu and 772002 ccpc网络赛 高斯消元法
传送门:hdu 5833 Zhu and 772002 题意:给n个数,每个数的素数因子不大于2000,让你从其中选则大于等于1个数相乘之后的结果为完全平方数 思路: 小于等于2000的素数一共也只有 ...
- bzoj-2338 2338: [HNOI2011]数矩形(计算几何)
题目链接: 2338: [HNOI2011]数矩形 Time Limit: 20 Sec Memory Limit: 128 MB Description Input Output 题意: 思路 ...
- POJ 3481Double Queue Splay
#include<stdio.h> #include<string.h> ; ],data[N],id[N],fa[N],size,root; void Rotate(int ...
- cookie 、session、JSESSIONID
cookie .session ? 让我们用几个例子来描述一下cookie和session机制之间的区别与联系.笔者曾经常去的一家咖啡店有喝5杯咖啡免费赠一杯咖啡的优惠,然而一次性消费5杯咖啡的机会微 ...
- java 8-8 接口的练习
/* 老师和学生案例,加入抽烟的额外功能 分析: 老师和学生都具有共同的变量:名字,年龄 共同的方法:吃饭,睡觉 老师有额外的功能:抽烟(设定个接口),部分抽烟 有共同的变量和方法,设一个父类:per ...
- 关于OAuth2.0的文章收集
http://blog.csdn.net/seccloud/article/details/8192707
- Masonry
Autolayout就像一个知情达理,善解人意的好姑娘,可惜长相有点不堪入目,所以追求者寥寥无几.所幸遇到了化妆大师cloudkite,给她来了一个完美的化妆,从此丑小鸭Autolayout变成了美天 ...
- PHP 魔术引号
1.魔术引号的作用是什么? 魔术引号设计的初衷是为了让从数据库或文件中读取数据和从请求中接收参数时,对单引号.双引号.反斜线.NULL加上一个一个反斜线进行转义,这个的作用跟addslashes( ...