调用外部API(HTTPS).net Framework 4.7.2 MVC --使用httpclient
调用外部API --使用httpclient
httpclient请求不属于浏览器操作,跨域是浏览器的安全性,不需要跨域
ajax是浏览器的操作,它需要进行设置跨域
1、httpclient请求https
.NET C# 使用HttpClient时忽略HTTPS证书
HttpClient 接口调用以及获取token 设置请求头
2、使用公共方法声明出httpclient对象(当前请求HTTPS,需要加入跨过证书验证)
public string beforeUrl = "https://192.XXX.X.XX/api"; /// <summary> /// 获取httpClient对象的公共方法 /// </summary> /// <param name="behindurl">请求路径后半部分</param> /// <param name="URLInfo">返回完整路径</param> /// <returns></returns> public HttpClient getHttpClient(string behindurl, out string URLInfo) { //如果请求对应api请求是https,跨过证书验证 var handler = new WebRequestHandler(); handler.ServerCertificateCustomValidationCallback = delegate { return true; }; //拼接完整路径 var URL = beforeUrl + behindurl; URLInfo = URL; var httpClient = new HttpClient(handler); httpClient.BaseAddress = new Uri(URL); //添加头 httpClient.DefaultRequestHeaders.Add("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTkxNDQ0NTUsImp0aSI6ImFkbWluIiwiaXNzIjoiamlhc2lvbiIsIm5iZiI6MTY2ODM4NjA1NSwic3ViIjoiSmlhc2lvbl9TZXJ2ZXJfRGV2In0.eoAhxLuUjbzzVfTlOK-YUn-Vspx4LleHHPwpzG9Y5NA"); return httpClient; }
C# .NET Core 使用HttpClient时忽略HTTPS证书
var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = delegate { return true; }; var client = new HttpClient(handler);
3、发送请求
--调用上面生成的httpclient对象实现调用第三方api增、删
/// <summary> /// 2.调第三方执行添加/修改 /// </summary> /// <param name="obj">第三方接口所需参数数据</param> /// <param name="urlstr">对应路径完整第三方api路径</param> /// 完整路径譬如:https://192.XX.X.XX/api/media/dir/new /// <returns></returns> public string send(object obj, string urlstr) { var resstr = ""; var httpclient = getHttpClient(urlstr, out string URLInfo); HttpContent content = new StringContent(JsonConvert.SerializeObject(obj), System.Text.Encoding.UTF8, "application/json"); //获取返回值 resstr = httpclient.PostAsync(URLInfo, content).Result.Content.ReadAsStringAsync().Result; return resstr; }
4、上传文件到第三方并保存到本地(示例为多文件上传)
.Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数
将文件信息放入httpclient传输需要将上传的文件放入 var content = new MultipartFormDataContent();中,然后使用resstr = httpclient.PostAsync(URL, content).Result.Content.ReadAsStringAsync().Result;进行传给第三方api
将上传文件放入MultipartFormDataContent()中需要将文件流转换为字节流
两种方式:
通过物理路径获取文件后获取字节流
//添加文件参数,参数名为files,文件名为123.png //向给第三方装入内容 content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(sSavePath)), "file", fileName);
通过上传的文件 HttpPostedFileBase f = Request.Files[i];直接转换为字节流
.Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数
for (int i = 0; i < Request.Files.Count; i++) { //获取上传文件流 HttpPostedFileBase f = Request.Files[i]; //将文件流转换为字节流 byte[] byteFileData =AVS_ToolsService.ReadFileBytes(f);//文件流转为字节流 调用ReadFileBytes方法 --参数为文件流 }
文件流转换为字节流方法
/// <summary> /// 文件流类型转化字节类型 /// </summary> /// <param name="fileData">文件流数据</param> /// <returns></returns> public static byte[] ReadFileBytes(HttpPostedFileBase fileData) { byte[] data; using (Stream inputStream = fileData.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); } return data; }
注意:要使用转字节流的方式必须SaveAs在前否则有错--不清楚原因暂时
会有错误
在使用字节获取详细信息的时候这里引发的错误
--------------------------------------------------------------------------------------------
//媒体上传 public ActionResult SaveFile(string id) { try { if (Request.Files.Count > 0) { string sSavePath = "";//本地保存文件路径 //用于放置文件信息 var content = new MultipartFormDataContent(); for (int i = 0; i < Request.Files.Count; i++) { var newfileName = ""; //获取上传文件 HttpPostedFileBase f = Request.Files[i]; string fileName = f.FileName; //获取本地要放置目录 string sBaseDir = getsaveDirPath(id, LoginUserInfo.sUserID); sSavePath = sBaseDir + "/m-" + newfileName + ".mp3"; //保存本地 f.SaveAs(sSavePath); //添加文件参数,参数名为files,文件名为123.png //向给第三方装入内容 content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(sSavePath)), "file", fileName); //向第三方api发送数据 var result=uploadFile(content,$"/media/file/upload?id={id}"); } } } catch (Exception ex) { return Content(ex.Message); } return Content(""); }
/// <summary> /// 本地放置目录位置 /// </summary> /// <param userId="">创建人id</param> /// <returns></returns> public string getsaveDirPath(string id, string userId) { //获取文件夹名称 var foldername = res.getfilenameById(id); string sBaseDir = "/upload/music/" + foldername + "/" + LoginUserInfo.sUserID + "/" + DateTime.Now.ToString("yyyyMM"); //判断是否存在,如果不存在自动创建 sBaseDir = Us.Core.FrameWork.UsMapPath.UsPath(sBaseDir); if (!Directory.Exists(sBaseDir)) { Directory.CreateDirectory(sBaseDir); } return sBaseDir; }
/// <summary> /// 3.上传文件到第三方 /// </summary> /// <param name="obj">文件内容</param> /// <returns></returns> public static KAPIResult uploadFile(HttpContent content, string behindurl) { var URL = beforeUrl + behindurl; var resstr = ""; var httpclient = getHttpClient(URL); //获取返回值 resstr = httpclient.PostAsync(URL, content).Result.Content.ReadAsStringAsync().Result; return resobj; }
5、获取程序的基目录(上传文件保存到本地使用的物理路径) --(控制器等都在这个文件下面)
c#获取当前运行程序所在的目录 - 腾讯云开发者社区-腾讯云 (tencent.com)
var s3 = System.AppDomain.CurrentDomain.BaseDirectory;
目前了解到的两个方法结果一样
var sf = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
本文来自博客园,作者:じ逐梦,转载请注明原文链接:https://www.cnblogs.com/ZhuMeng-Chao/p/16891306.html