开源data内容)

日常做网抓数据,都是以GET请求为主,偶尔遇到需要POST请求的,一般POST的参数只是一串字符串就可以了,通过构造字符串也很容易完成,但此次SM.MS的API接口要求是Content-Type: multipart/form-data,同时上传图片的同时还要加入一些控制参数,针对此类型的POST请求,以下给大家做一简单介绍。

百度不到找谷歌

用POST multipart/form-data 之类的关键字,翻了好一轮百度,本想着中文博客阅读容易省点时间,抄回来的代码都不能用,最后倒贴了不少无用功的时间,没找到答案。

真心想解决问题,不google一下,还真的不行,许多非专业开发者可能还不知道怎样上google,有这方面需求,可私信笔者,笔者可以给一点点指引。

在google上,很容易翻到答案,最终找到了最优解,用RestSharp来解决,同时附上找到的一些不错的链接,供大家深入去学习下。

https://csharp.hotexamples.com/examples/RestSharp/RestRequest/AddFile/php-restrequest-addfile-method-examples.html

https://briangrinstead.com/blog/multipart-form-post-in-c/

https://github.com/jptoto/MultipartFormPoster

https://stackoverflow.com/questions/19954287/how-to-upload-file-to-server-with-http-post-multipart-form-data

项目使用.net 4.5的话,可以用HttpClient类库,貌似实现出来也比较容易,但作为桌面端应用,要求.net 4.5有点高,只能找.net 4.0下的RestSharp方案了(在nuget上要使用105版本才可以支持,最新的也不支持.net 4.0)。

说了这么久,该上代码的时候了。


开源-SM.MS图床API调用(用POST上传multipart/form-data内容)


API参数要求

代码如下:

···

private static string GetUploadedPictureInfo(string filePath)

 {
 string url = "https://sm.ms/api/upload";
 var client = new RestClient(url);
 client.Timeout = 3000;
 var request = new RestRequest(Method.POST);
 request.AddFile("smfile", File.ReadAllBytes(filePath), Path.GetFileName(filePath));
 request.AlwaysMultipartFormData = true;
 request.AddParameter("ssl", "true", ParameterType.GetOrPost);
 var result = client.Execute(request);
 if (result.StatusCode == System.Net.HttpStatusCode.OK)
 {
 return result.Content;
 }
 else
 {
 return string.Empty;
 }
 }

···

展开阅读全文

页面更新:2024-04-13

标签:能用   私信   开发者   用功   字符串   中文   笔者   接口   日常   关键字   桌面   答案   参数   代码   时间   内容   数码

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top