.net4.0 调用API(form-data)上传文件及传参

/// <summary>

///

/// </summary>

/// <param name="url">API URL</param>

/// <param name="token">API token</param>

/// <param name="parameters">API参数(除文件类型外)</param>

/// <param name="fileContent">文件参数(二进制文件流)</param>

/// <param name="fileName">文件名</param>

/// <returns></returns>

public string Post_formdata(string url, string token, Dictionary<string, string> parameters, byte[] fileContent, string fileName)

{

string result = "";

string strBoundary = "--" + DateTime.Now.Ticks.ToString("x");//程序生成

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST";

if (!string.IsNullOrEmpty(token))

{

WebHeaderCollection coll = new WebHeaderCollection();

coll.Add("token", token);

request.Headers = coll;

}

request.ContentType = "multipart/form-data;charset=UTF-8; boundary=" + strBoundary;

// 设置请求参数

StringBuilder sb = new StringBuilder();

foreach (KeyValuePair<string, string> kvp in parameters)

{

sb.AppendFormat("--" + strBoundary + "\r\n");

sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n", kvp.Key);

sb.AppendFormat("\r\n{0}\r\n", kvp.Value);

}

// 上传文件

sb.AppendFormat("--" + strBoundary + "\r\n");

sb.AppendFormat("Content-Disposition: form-data; name=\"uploadFile\"; filename=\"{0}\"\r\n", fileName); //uploadFile为参数名

//sb.AppendFormat("Content-Type: image/png\r\n");

sb.AppendFormat("Content-Type: octet-stream\r\n");

sb.AppendFormat("\r\n");

byte[] paramBytes= Encoding.UTF8.GetBytes(sb.ToString());

var footerBytes = Encoding.UTF8.GetBytes("\r\n--" + strBoundary + "--\r\n");

byte[] fileBytes = fileContent;

request.ContentLength += fileBytes.Length + paramBytes.Length + footerBytes.Length + 1;

using (Stream requestStream = request.GetRequestStream())

{

requestStream.Write(paramBytes, 0, paramBytes.Length);

requestStream.Write(fileBytes, 0, fileBytes.Length);

requestStream.Write(footerBytes, 0, footerBytes.Length);

}

HttpWebResponse resp;

try

{

resp = (HttpWebResponse)request.GetResponse();

}

catch (WebException ex)

{

resp = (HttpWebResponse)ex.Response;

}

Stream stream = resp.GetResponseStream();

//获取响应内容

using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))

{

result = reader.ReadToEnd();

}

resp.Close();

request.Abort();

return result;

}

相关推荐
数据小爬虫@2 分钟前
如何利用PHP爬虫获取速卖通(AliExpress)商品评论
开发语言·爬虫·php
yngsqq39 分钟前
cad c# 二次开发 ——动态加载dll 文件制作(loada netloadx)
c#
java1234_小锋1 小时前
MyBatis如何处理延迟加载?
java·开发语言
FeboReigns1 小时前
C++简明教程(10)(初识类)
c语言·开发语言·c++
学前端的小朱1 小时前
处理字体图标、js、html及其他资源
开发语言·javascript·webpack·html·打包工具
摇光932 小时前
js高阶-async与事件循环
开发语言·javascript·事件循环·宏任务·微任务
沐泽Mu2 小时前
嵌入式学习-QT-Day09
开发语言·qt·学习
小猿_002 小时前
C语言实现顺序表详解
c语言·开发语言
余~~185381628002 小时前
NFC 碰一碰发视频源码搭建技术详解,支持OEM
开发语言·人工智能·python·音视频
GOATLong3 小时前
c++智能指针
开发语言·c++