C#,HttpWebRequest模拟发送Post请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#,HttpWebRequest模拟发送Post请求相关的知识,希望对你有一定的参考价值。

RT,发送请求的时候有参数,但是图一表示应该只有一个Form表单吧,但是发送请求之后返回的不是需要的信息,应该是请求的参数错误,所以,这里的参数到底应该怎么传

HttpWebRequest模拟发送Post请求,直接上代码,看例子

1、建立请求函数

/// <summary> 
/// POST请求与获取结果 
/// </summary> 
public static string HttpPost(string Url, string postDataStr) 
 
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
  request.Method = "POST"; 
  request.ContentType = "application/x-www-form-urlencoded"; 
  request.ContentLength = postDataStr.Length; 
  StreamWriter writer = new StreamWriter(request.GetRequestStream(),Encoding.ASCII); 
  writer.Write(postDataStr); 
  writer.Flush(); 
  HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
  string encoding = response.ContentEncoding; 
  if (encoding == null || encoding.Length < 1)  
    encoding = "UTF-8"; //默认编码 
   
  StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); 
  string retString = reader.ReadToEnd(); 
  return retString;

2、调用例子

static void Main(string[] args) 
 
  string url = "http://www.mystudy.cn/LoginHandler.aspx"; 
  string data = "UserName=admin&Password=123"; 
  string result = HttpPost(url, data); 
  Console.WriteLine(result); 
  Console.ReadLine(); 

3、换成你的参数即可

参考技术A key=value&key1=value1
记得格式化字符串

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\\n1";           

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;     

参考技术A 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;
参考技术B 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\n1";
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;

参考技术C 你说的这个应该是标准的文件上传。
可以使用 System.Net.WebClient.UploadFile方法。追问

用这个方法提交还是不行,返回:远程服务器返回错误: (500) 内部服务器错误。
和我使用string提交是同一个返回错误,这表示发送过去的数据类型不匹配

追答

你先建一个普通的html文本,用form表单去提交,看能否成功。

追问

已经不需要了。对方的这个接口根本没开放走不通。

本回答被提问者和网友采纳

以上是关于C#,HttpWebRequest模拟发送Post请求的主要内容,如果未能解决你的问题,请参考以下文章

c# HttpWebRequest 模拟HTTP post 传递JSON参数

转asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

C#模拟HTTP请求Post JSON

C# 模拟 post提交php页面的表单

C# 利用HttpWebRequest进行HTTPS的post请求的示例

c# httpwebrequest 模拟登陆