gpt4 book ai didi

c# - HttpWebResponse 的编码问题

转载 作者:可可西里 更新时间:2023-11-01 17:13:29 25 4
gpt4 key购买 nike

使用 Fiddler 运行以下代码显示加号正在转换为某种空白字符。我应该使用什么编码来防止数据被转换?我想保留加号等。

编辑:更新的代码示例

string postData = "test1=test+plussign&test2=another++twoplussigns";
private static byte[] EncodePostData(string postData)
{
StringBuilder sb = new StringBuilder();

string[] pairs = postData.Split('&');
foreach (string pair in pairs)
{
string key = Uri.EscapeDataString(pair.Split('=')[0]);
string value = Uri.EscapeDataString(pair.Split('=')[1]);

sb.AppendFormat("{0}={1}&",key, value);
}
sb.Remove(sb.Length - 1, 1);

return HttpUtility.UrlEncodeToBytes(sb.ToString());
}

调用方法如下

byte[] data = EncodePostData(postData);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.0.3) Gecko/2008092510 Ubuntu/8.04 (hardy) Firefox/3.03";
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
ServicePointManager.Expect100Continue = false;

Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();

HttpWebResponse Response = (HttpWebResponse)request.GetResponse();
Response.Close();

最佳答案

由于您的变量名为 postData,我假设您正在向 Web 服务器发送 HTTP POST。

Wikipedia's summary HTTP POST 的规则是:

When a web browser sends a POST request from a web form element, the default Internet media type is "application/x-www-form-urlencoded". This is a format for encoding key-value pairs with possibly duplicate keys. Each key-value pair is separated by an '&' character, and each key is separated from its value by an '=' character. Keys and values are both escaped by replacing spaces with the '+' character and then using URL encoding on all other non-alphanumeric characters.

也就是说,HTTP POST 主体中 '+' 的默认解释是编码的 ' ' 字符。您需要通过调用 Uri.EscapeDataString 正确转义数据或 HttpUtility.UrlEncode .

Uri.EscapeDataString("test+PlusSigns"); // returns "test%2BPlusSigns"

或者,使用 HttpUtility.UrlEncodeToBytes并将生成的字节直接写入请求流(不使用 StreamWriter)。

(请注意,如果您要发送键/值对,则需要分别对每个键和值进行转义,然后使用 '=''&' 将它们连接起来字符。)

关于c# - HttpWebResponse 的编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8707999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com