如果你需要post一个form-data到后台,使用multipart/form-data,需要使用boundary来格式化,
一般百度到的都是直接分开写入请求流里面,我这个先组织好字符串后直接写入流。
还有现在用application/x-www-form-urlencoded;charset=utf-8格式化的多。组织起来比较简单:
apiInput.Body = $"CMD={cmd}&AppId={appId}&AppCode={appCode}&Data={cert}";
下面是c#,参考代码。
public string boundary = "----" + DateTime.Now.Ticks.ToString("x");
ContentType = $"multipart/form-data;boundary={boundary}"
//var ds = new Dictionary<string, string>();
//ds.Add("CMD", cmd);
//ds.Add("AppId", appId);
//ds.Add("AppCode", appCode);
//ds.Add("Data", cert);
//apiInput.Body = generateFormDataString(ds, boundary);
private static string generateFormDataString(Dictionary<string, string> props,string boundary)
{
StringBuilder sb = new StringBuilder();
//var beginBoundary = string.Format("--{0}\r\n", boundary);
var endBoundary = string.Format("--{0}--", boundary);
//var sortdir = props.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
int i = 0;
//sb.Append(beginBoundary);
foreach (var item in props)
{
sb.Append("--" + boundary + "\r\n");
sb.Append("Content-Disposition: form-data; name=\"" + item.Key + "\"\r\n");
sb.Append("\r\n");
sb.Append(item.Value + "\r\n");
//sb.Append(string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n{2}",
// item.Key, item.Value, boundary));
i++;
}
sb.Append(endBoundary);
return sb.ToString();
}