framework3.5以上
System.Net.WebClient WebClientObj = new System.Net.WebClient();
System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
PostVars.Add("A1","1");
PostVars.Add("A2","2");
PostVars.Add("A3","3");
try
{
byte[] byRemoteInfo = WebClientObj.UploadValues("http://xxx/xx","POST",PostVars);
string result= System.Text.Encoding.Default.GetString(byRemoteInfo);
}
catch
{
}
framework3.5
public static string UploadMultipartFormData(string url, string httpMethod, Dictionary<string, string> headers, NameValueCollection nameValueCollection, NameValueCollection fileCollection)
{
var boundary = string.Format("batch_{0}", Guid.NewGuid());
var startBoundary = string.Format("--{0}", boundary);
// Set up Request body.
WebRequest request = HttpWebRequest.Create(url);
foreach (var item in headers)
{
request.Headers.Add(item.Key, item.Value);
}
request.Method = httpMethod;
request.ContentType = "multipart/form-data; boundary=" + boundary;
// Writes the boundary and Content-Disposition header, then writes
// the file binary, and finishes by writing the closing boundary.
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
// 处理文件内容
string[] fileKeys = fileCollection.AllKeys;
foreach (string key in fileKeys)
{
WriteFileToStream(writer, startBoundary, key, fileCollection[key]);
}
// 键值对参数
string[] allKeys = nameValueCollection.AllKeys;
foreach (string key in allKeys)
{
WriteNvToStream(writer, startBoundary, key, nameValueCollection[key]);
}
var endFormData = CRLF + string.Format("--{0}--", boundary) + CRLF;
writer.Write(endFormData);
writer.Flush();
writer.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
return json;
}
static void WriteFileToStream(StreamWriter writer, string startBoundary, string name, string filePath)
{
var filename = Path.GetFileName(filePath);
var fileRequestBody = startBoundary + CRLF;
fileRequestBody += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"" + CRLF + CRLF;
writer.Write(fileRequestBody);
writer.Flush();
byte[] bmpBytes = File.ReadAllBytes(filePath);
writer.BaseStream.Write(bmpBytes, 0, bmpBytes.Length);
}
static void WriteNvToStream(StreamWriter writer, string startBoundary, string name, string value)
{
var nvFormData = CRLF + startBoundary + CRLF;
nvFormData += "Content-Disposition: form-data; name=\"" + name + "\"" + CRLF + CRLF;
nvFormData += value /*+ CRLF*/;
writer.Write(nvFormData);
writer.Flush();
}