HttpWebRequest发送post请求时有多个参数如何处理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpWebRequest发送post请求时有多个参数如何处理相关的知识,希望对你有一定的参考价值。
参考技术A 下面是一个测试,你可以完全拷贝下来进行测试asmx代码
<%@ WebService Language="C#" Class="Service1" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
[WebMethod]
public string doSearch(String p1,String p2,String p3)
return "Hello World" + p1 + p2 + p3;
winform代码
private void button1_Click(object sender, EventArgs e)
string strURL = "http://localhost:2852/WebSite1/Service1.asmx/doSearch";
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
// 内容类型
request.ContentType = "application/x-www-form-urlencoded";
//这是原始代码:
string paraUrlCoded = "p1=x&p2=y&p3=测试的中文";
byte[] payload;
//将URL编码后的字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的 ContentLength
request.ContentLength = payload.Length;
//获得请 求流
Stream writer = request.GetRequestStream();
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
// 关闭请求流
writer.Close();
System.Net.HttpWebResponse response;
// 获得响应流
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
XmlDocument d = new XmlDocument();
d.Load(s);
MessageBox.Show(d.DocumentElement.InnerText);
读取 HttpWebRequest 的 HTTP POST 请求
【中文标题】读取 HttpWebRequest 的 HTTP POST 请求【英文标题】:Read the HTTP POST request of HttpWebRequest 【发布时间】:2012-08-02 00:53:31 【问题描述】:我需要为我正在编写的一些测试创建 Http POST 请求和一些 GET 请求作为字符串。目前,我的测试使用 StringBuilder 构建它们,并且从提琴手中提取的硬编码 POST 请求有点像这样:
var builder = new StringBuilder();
builder.Append("POST https://some.web.pg HTTP/1.1\r\n");
builder.Append("Content-Type: application/x-www-form-urlencoded\r\n");
builder.Append("Referer: https://some.referer.com\r\n");
builder.Append("Accept-Language: en-us\r\n");
builder.Append("Accept-Encoding: gzip, deflate\r\n");
builder.Append("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)\r\n");
builder.Append("Host: login.yahoo.com\r\n");
// ... other header info
builder.Append("\r\n");
builder.Append("post body......\r\n");
var postData = builder.ToString();
这很快使我的测试变得混乱,并且希望有一种更简洁的方式来构建这些 POST 请求。我一直在研究 HttpWebRequest 类,希望它可以为我创建这些。我认为,它必须有某种方式来构建这个我试图以某种形式创建的确切请求。但可惜的是,GetRequestStream 是一个只可写的流。
有没有办法读取 HttpWebRequest 将生成的请求流(然后将其更改为字符串)?甚至任何关于如何生成这些 POST 请求的想法都可以。
【问题讨论】:
【参考方案1】: HttpWebRequest req = (HttpWebRequest)WebRequest.Create(yoururllink);
var c = HttpContext.Current;
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
string strResponse_copy = strRequest; //Save a copy of the initial info sent from your url link
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
//req.Proxy = proxy;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
【讨论】:
【参考方案2】:我建议您使用模拟,因为它是单元测试的最佳实践: 在堆栈上看到这个答案 Unit testing HTTP requests in c#
【讨论】:
【参考方案3】:这里是一个用于发出 Get 请求的 msdn 示例:
using System;
使用 System.Net; 使用 System.IO;
命名空间 MakeAGETRequest_charp /// /// Class1 的摘要描述。 /// 类 Class1 静态无效主要(字符串 [] 参数) 字符串网址; sURL = "http://www.microsoft.com";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
WebProxy myProxy = new WebProxy("myproxy",80);
myProxy.BypassProxyOnLocal = true;
wrGETURL.Proxy = WebProxy.GetDefaultProxy();
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string sLine = "";
int i = 0;
while (sLine!=null)
i++;
sLine = objReader.ReadLine();
if (sLine!=null)
Console.WriteLine("0:1",i,sLine);
Console.ReadLine();
这里是一个 for post 请求(来自HTTP request with post)
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("http:\\domain.com\page.asp");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream newStream = httpWReq.GetRequestStream())
newStream.Write(data,0,data.Length);
【讨论】:
以上是关于HttpWebRequest发送post请求时有多个参数如何处理的主要内容,如果未能解决你的问题,请参考以下文章
使用 C# 和 HttpWebRequest 向端点发送 POST 请求
HttpWebRequest 自定义header,Post发送请求,请求形式是json,坑爹的代码
C# 利用HttpWebRequest进行HTTPS的post请求的示例