c#http 请求接口 类型From-data
转发请注明由来
public static class HttpClientHelper
{
public static int count = 0;
///
/// Http web 请求 类型From-data
///
/// 请求路径
/// 参数字典类型
/// 是否文件
///
public static string postFileMessage(string Url, Dictionary<string,string> keys,bool isfile)
{
try
{
string responseContent = “”;
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(Url);
// 边界符
var boundary = “---------------” + DateTime.Now.Ticks.ToString(“x”);
// 边界符
var beginBoundary = Encoding.ASCII.GetBytes("–" + boundary + “\r\n”);
// 最后的结束符
var endBoundary = Encoding.ASCII.GetBytes("–" + boundary + “–\r\n”);
memStream.Write(beginBoundary, 0, beginBoundary.Length);
// 设置属性
webRequest.Method = “POST”;
webRequest.Timeout = 10000;
webRequest.ContentType = “multipart/form-data; boundary=” + boundary;
foreach (KeyValuePair<string, string> kvp in keys)
{
count += 1;
// 写入文件
if (isfile)
{
var fileStream = new FileStream(kvp.Value, FileMode.Open, FileAccess.Read);
const string filePartHeader =
“Content-Disposition: form-data; name=”{0}"; filename="{1}"\r\n" +
“Content-Type: application/octet-stream\r\n\r\n”;
var header = string.Format(filePartHeader, kvp.Key, kvp.Value);
var headerbytes = Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
string end = “\r\n”;
headerbytes = Encoding.UTF8.GetBytes(end);
memStream.Write(headerbytes, 0, headerbytes.Length);
fileStream.Close();
}
else
{
// 写入字符串的Key
var stringKeyHeader = “Content-Disposition: form-data; name=”{0}"" +
“\r\n\r\n{1}\r\n”;
var header = string.Format(stringKeyHeader, kvp.Key, kvp.Value);
var headerbytes = Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
}
if (count != keys.Count - 1)
memStream.Write(beginBoundary, 0, beginBoundary.Length);
else
// 写入最后的结束边界符
memStream.Write(endBoundary, 0, endBoundary.Length);
}
webRequest.ContentLength = memStream.Length;
var requestStream = webRequest.GetRequestStream();
memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
using (HttpWebResponse res = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream resStream = res.GetResponseStream())
{
byte[] buffer = new byte[1024];
int read;
while ((read = resStream.Read(buffer, 0, buffer.Length)) > 0)
{
responseContent += Encoding.UTF8.GetString(buffer, 0, read);
}
}
res.Close();
}
return responseContent;
}
catch (Exception e)
{
ToolBox.LogTools.PubliceLog.WriteLog("请求失败: 异常" + e.Message);
}
return null;
}
}
#创作不易请打赏!!!!!!!!!!!