C#HttpWebRequest类型为"application/x-www-form-urlencoded" - 如何在内容体中发送'&'字符?

nel*_*shh 32 c# post httpwebrequest

我正在用C#编写一个API连接的小应用程序.

我连接到一个API,它有一个采用长字符串的方法,即日历(ics)文件的内容.

我是这样做的:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.AllowAutoRedirect = false;
request.CookieContainer = my_cookie_container;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.ContentType = "application/x-www-form-urlencoded";

string iCalStr = GetCalendarAsString();

string strNew = "&uploadfile=true&file=" + iCalStr;

using (StreamWriter stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
 {
     stOut.Write(strNew);
     stOut.Close();
 }
Run Code Online (Sandbox Code Playgroud)

这似乎很有效,直到我在我的日历中添加一些特定的HTML.

如果我在我的日历(或类似)中的某个地方有一个' ',那么服务器只会获得所有数据到'&' - 点,所以我假设'&'使得它看起来像这个点之后的任何东西属于一个新参数?

我怎样才能解决这个问题?

Toh*_*hid 37

首先安装" Microsoft ASP.NET Web API Client "nuget包:

  PM > Install-Package Microsoft.AspNet.WebApi.Client
Run Code Online (Sandbox Code Playgroud)

然后使用以下函数发布您的数据:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是如何使用它:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);
Run Code Online (Sandbox Code Playgroud)

要么

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result
Run Code Online (Sandbox Code Playgroud)

或(不推荐)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;
Run Code Online (Sandbox Code Playgroud)


And*_*ite 26

由于您的内容类型是application/x-www-form-urlencoded您需要对POST正文进行编码,特别是如果它包含&在表单中具有特殊含义的字符.

尝试将字符串传递给HttpUtility.UrlEncode,然后再将其写入请求流.

这里有几个链接供参考.


Jus*_*ner 8

只要服务器允许对ampresand字符进行POST(并非所有操作都不安全),您只需要对URL进行编码.在放大器的情况下,你应该用%26.替换字符.

.NET为您提供了一种编码整个字符串的好方法:

string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);
Run Code Online (Sandbox Code Playgroud)