与POST编码问题C#web请求 [英] C# web request with POST encoding question

查看:138
本文介绍了与POST编码问题C#web请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSDN网站有一些C#代码显示如何使的例子与POST'ed数据的Web请求。下面是该代码的摘录:

On the MSDN site there is an example of some C# code that shows how to make a web request with POST'ed data. Here is an excerpt of that code:

WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
request.Method = "POST";
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData); // (*)
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
WebResponse response = request.GetResponse ();
...more...



线条为标志( *)是困扰我就行了。不应该将数据使用以UrlEncode方法,而不是UTF8编码?这不就是应用程序/ x-WWW窗体-urlencoded 暗示?

The line marked (*) is the line that puzzles me. Shouldn't the data be encoded using the UrlEncode method rather than UTF8? Isn't that what application/x-www-form-urlencoded implies?

推荐答案

的示例代码是一种误导,因为的Con​​tentType设置为应用程序/ x-WWW窗体-urlencoded,但实际内容是纯文本。应用程序/ x-WWW窗体-urlencoded是一个字符串这样的:

The sample code is misleading, because ContentType is set to application/x-www-form-urlencoded but the actual content is plain text. application/x-www-form-urlencoded is a string like this:

name1=value1&name2=value2



以UrlEncode函数用于逃避特殊字符,如'和;'和'='这样的分析器不考虑他们作为语法。它需要一个字符串(媒体类型text /纯),并返回一个字符串(媒体类型application / x-WWW窗体-urlencoded)。

The UrlEncode function is used to escape especial characters like '&' and '=' so a parser doesn't consider them as syntax. It takes a string (media type text/plain) and returns a string (media type application/x-www-form-urlencoded).

Encoding.UTF8.GetBytes是用来转换字符串(媒体类型application / x-WWW窗体-urlencoded在我们的例子)成字节数组,这是WebRequest的API所期待的。

Encoding.UTF8.GetBytes is used to convert the string (media type application/x-www-form-urlencoded in our case) into an array of bytes, which is what the WebRequest API expects.

这篇关于与POST编码问题C#web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆