c#如何post文件流

我是调用其他人的接口碰到了这样的问题。我是使用HttpWebRequest类进行post发送的,我发送xml字符串的时候是这样的:stringstrPost="a="+a... 我是调用其他人的接口碰到了这样的问题。
我是使用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类型。求解
展开
 我来答
百度网友edabfc9
2018-04-12 · TA获得超过2740个赞
知道小有建树答主
回答量:0
采纳率:0%
帮助的人:0
展开全部

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; }    }}

xiangjuan314
2016-01-11 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2928万
展开全部
protected string GetWebContent(string url)
{
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;
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
zhuguofu2004
2015-09-02 · TA获得超过4万个赞
知道大有可为答主
回答量:7308
采纳率:86%
帮助的人:1059万
展开全部
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; }
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
超大蒲公英
2014-12-02 · TA获得超过741个赞
知道小有建树答主
回答量:758
采纳率:75%
帮助的人:744万
展开全部
你说的这个应该是标准的文件上传。
可以使用 System.Net.WebClient.UploadFile方法。
更多追问追答
追问
用这个方法提交还是不行,返回:远程服务器返回错误: (500) 内部服务器错误。
和我使用string提交是同一个返回错误,这表示发送过去的数据类型不匹配
追答
你先建一个普通的html文本,用form表单去提交,看能否成功。
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式