这个一直研究了很久,通过json字符串解析成键值对,再添加到Http请求中,经过测试可以正常接收数据。
封装了方法文章来源:https://www.toymoban.com/news/detail-514152.html
public string HttpPost(string url, string jsonStr)
{
string content = "";
try
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
request.Timeout = -1;
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("member", "secret"));
request.Credentials = credentialCache;
request.ServicePoint.Expect100Continue = false;
Dictionary<string, string> map = JsonStringToKeyValuePairs(jsonStr);
using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (map != null)
{
foreach (string key in map.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, map[key]);
byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responsestream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responsestream))
{
content = sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
content = ex.Message ;
}
return content;
}
public static Dictionary<string, string> JsonStringToKeyValuePairs(string jsonStr)
{
char jsonBeginToken = '{';
char jsonEndToken = '}';
if (string.IsNullOrEmpty(jsonStr))
{
return null;
}
//验证json字符串格式
if (jsonStr[0] != jsonBeginToken || jsonStr[jsonStr.Length - 1] != jsonEndToken)
{
throw new ArgumentException("非法的Json字符串!");
}
var resultDic = new Dictionary<string, string>();
var jobj = JObject.Parse(jsonStr);
JsonOn(jobj, resultDic);
return resultDic;
}
private static Dictionary<string, string> JsonOn(JToken jobT, Dictionary<string, string> Dic)
{
//找出包含嵌套的字段列
if (jobT is JObject jobj && jobj.Properties().Count() > 0)
{
foreach (var item in jobj.Properties())
{
JsonProperties(item, Dic);
}
}
else
{
Dic.Add(jobT.Path, jobT.ToString());
return Dic;
}
return Dic;
}
private static Dictionary<string, string> JsonProperties(JProperty jobj, Dictionary<string, string> Dic)
{
return JsonOn(jobj.Value, Dic);
}
还有另一种简单的方法文章来源地址https://www.toymoban.com/news/detail-514152.html
public string HttpPost(string urlStr, string jsonStr)
{
string content = "";
try
{
Dictionary<string, string> map = JsonStringToKeyValuePairs(jsonStr);
var mfdc = new System.Net.Http.MultipartFormDataContent();
mfdc.Headers.Add("ContentType", "multipart/form-data");//声明头部
foreach (string key in map.Keys)
{
mfdc.Add(new System.Net.Http.StringContent(map[key]), key);//参数, 内容在前,参数名称在后
}
var clientTask = new System.Net.Http.HttpClient().PostAsync(urlStr, mfdc);//发起异步请求
clientTask.Wait();//等待请求结果
if (clientTask.Result.IsSuccessStatusCode)
{
//请求正常
var resultTask = clientTask.Result.Content.ReadAsStringAsync();//异步读取返回内容
resultTask.Wait();//等读取返回内容
content = resultTask.Result;//返回内容字符串
}
else
{
//请求异常
content = "失败";
}
}
catch (Exception ex)
{
content = ex.Message;
}
return content;
}
到了这里,关于c#HTTP使用form-data发送请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!