c#如何post文件流
我是使用HttpWebRequest类进行post发送的,我发送xml字符串的时候是这样的:
string strPost="a="+a+"&b="+strXML;
byte[] data = Encoding.GetEncoding("GBK").GetBytes(strPost);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentLength = data.Length;
//发送报文
Stream smRequest = httpRequest.GetRequestStream();
smRequest.Write(data, 0, data.Length);
smRequest.Close();
//接收回执报文
Stream smResponse = httpRequest.GetResponse().GetResponseStream();
using (StreamReader responseReader =
new StreamReader(smResponse, Encoding.GetEncoding("GBK")))
{
strResult = responseReader.ReadToEnd();
}
smResponse.Close();
这样发送过去对方的接口是可以接受xml的字符串。后来我在做另外一个接口的时候是传递文件流。我看了下对方接受b这个参数的类型是CommonsMultipartFile(JAVA的接口)。也就是我把文件流转换为string字符串传过去那个接口是不接收的。直接报远程服务器返回错误: (500) 内部服务器错误。
所以C#要怎么POST文件流给对方。肯定不能像我上面写的那样string strPost="a="+a+"&b="+FileStream;
注意,a这个参数是string,b参数传递的是file类型。求解 展开
C#中post用法如下:
首先,POST请求会把请求的数据放置在HTTP请求包的包体中。
其次,POST,由于不是URL传值,理论上是不会受限制的,但是实际上各个服务器会规定对POST提交数据大小进行限制,Apache、IIS都有各自的配置。
最后,POST的安全性较高。
通过C#post文件流的如下代码为:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;using System.Net;
using System.Text;
public class HttpPost{
/// <summary> ///
以Post 形式提交数据到 uri
/// </summary> ///
<param name="uri">
</param>
/// <param name="files">
</param>
/// <param name="values"></param>
/// <returns></returns>
public static byte[] Post(Uri uri, IEnumerable<UploadFile> files, NameValueCollection values) {
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
MemoryStream stream = new MemoryStream();
byte[] line = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//提交文本字段
if (values != null)
{
string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach (string key in values.Keys)
{
string s = string.Format(format, key, values[key]);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
}
stream.Write(line, 0, line.Length); }
//提交文件
if (files != null)
{
string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
foreach (UploadFile file in files)
{ string s = string.Format(fformat, file.Name, file.Filename);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
stream.Write(file.Data, 0, file.Data.Length);
stream.Write(line, 0, line.Length);
} }
request.ContentLength = stream.Length;
Stream requestStream = request.GetRequestStream();
stream.Position = 0L;
stream.CopyTo(requestStream);
stream.Close();
requestStream.Close();
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var mstream = new MemoryStream())
{ responseStream.CopyTo(mstream);
return mstream.ToArray(); } }
/// <summary> /// 上传文件
/// </summary>
public class UploadFile
{
public UploadFile()
{
ContentType = "application/octet-stream"; }
public string Name { get; set; }
public string Filename { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; } }}
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
// 要注意的这是这个编码方式,还有内容的Xml内容的编码方式
Encoding encoding = Encoding.GetEncoding("GBK");
byte[] data = encoding.GetBytes(url);
// 准备请求,设置参数
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
//request.ContentType = "text/plain";
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Flush();
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
}
Post提交xml
private string PostXml(string url, string strPost)
{
string result = "";
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "text/xml";//提交xml
//objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
public class HttpPost
{
/// <summary>
/// 以Post 形式提交数据到 uri
/// </summary>
/// <param name="uri"></param>
/// <param name="files"></param>
/// <param name="values"></param>
/// <returns></returns>
public static byte[] Post(Uri uri, IEnumerable<UploadFile> files, NameValueCollection values)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
MemoryStream stream = new MemoryStream();
byte[] line = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//提交文本字段
if (values != null)
{
string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach (string key in values.Keys)
{
string s = string.Format(format, key, values[key]);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
}
stream.Write(line, 0, line.Length);
}
//提交文件
if (files != null)
{
string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
foreach (UploadFile file in files)
{
string s = string.Format(fformat, file.Name, file.Filename);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);
stream.Write(file.Data, 0, file.Data.Length);
stream.Write(line, 0, line.Length);
}
}
request.ContentLength = stream.Length;
Stream requestStream = request.GetRequestStream();
stream.Position = 0L;
stream.CopyTo(requestStream);
stream.Close();
requestStream.Close();
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var mstream = new MemoryStream())
{
responseStream.CopyTo(mstream);
return mstream.ToArray();
}
}
/// <summary>
/// 上传文件
/// </summary>
public class UploadFile
{
public UploadFile()
{
ContentType = "application/octet-stream";
}
public string Name { get; set; }
public string Filename { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
}
}
可以使用 System.Net.WebClient.UploadFile方法。
用这个方法提交还是不行,返回:远程服务器返回错误: (500) 内部服务器错误。
和我使用string提交是同一个返回错误,这表示发送过去的数据类型不匹配
你先建一个普通的html文本,用form表单去提交,看能否成功。