月夜钓钱江鱼

醉后不知天在水,满船清梦压星河。

以下是使用C#中的HttpWebRequest发送post请求的示例代码,请求头为form-data,可以上传文件。你可以将它封装成一个通用的方法。

 1 public static string HttpPost(string url, Dictionary<string, string> parameters, Dictionary<string, string> files)
 2 {
string strBoundary = "qwwg-" + DateTime.Now.Ticks.ToString("x");//程序生成
3 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 4 request.Method = "POST"; 5 request.ContentType = "multipart/form-data;charset=UTF-8; boundary=" + strBoundary; 6 7 // 设置请求参数 8 StringBuilder sb = new StringBuilder(); 9 foreach (KeyValuePair<string, string> kvp in parameters) 10 { 11 sb.AppendFormat("--"+ strBoundary + "\r\n");12 sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n", kvp.Key); 13 sb.AppendFormat("\r\n{0}\r\n", kvp.Value); 14 } 15 16 // 上传文件 17 foreach (KeyValuePair<string, string> kvp in files) 18 { 19 sb.AppendFormat("--"+ strBoundary + "\r\n");20 sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", kvp.Key, Path.GetFileName(kvp.Value)); 21 sb.AppendFormat("Content-Type: image/png\r\n"); 22 sb.AppendFormat("\r\n"); 23 24 byte[] fileBytes = File.ReadAllBytes(kvp.Value); 25 request.ContentLength += fileBytes.Length; 26 27 using (Stream requestStream = request.GetRequestStream()) 28 { 29 requestStream.Write(Encoding.UTF8.GetBytes(sb.ToString()), 0, sb.Length); 30 requestStream.Write(fileBytes, 0, fileBytes.Length); 31 requestStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, 2); 32 33 // 发送请求并返回响应 34 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 35 using (StreamReader sr = new StreamReader(response.GetResponseStream())) 36 { 37 return sr.ReadToEnd(); 38 } 39 } 40 } 41 }

调用示例:

1 string url = "http://example.com/upload";
2 Dictionary<string, string> parameters = new Dictionary<string, string>();
3 parameters["username"] = "user123";
4 parameters["password"] = "123456";
5 Dictionary<string, string> files = new Dictionary<string, string>();
6 files["avatar"] = @"C:\avatar.png";
7 string result = HttpPost(url, parameters, files);

测试结果:

底层示例数据:

另外方法:

 

posted on 2023-11-30 17:29  湘灵  阅读(3077)  评论(8编辑  收藏  举报