简体   繁体   English

类型为“application/x-www-form-urlencoded”的 C# HttpWebRequest - 如何在内容正文中发送“&”字符?

[英]C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

I'm writing a small API-connected application in C#.我正在用 C# 编写一个小的 API 连接应用程序。

I connect to a API which has a method that takes a long string, the contents of a calendar(ics) file.我连接到一个 API,它有一个方法,它需要一个长字符串,一个日历(ics)文件的内容。

I'm doing it like this:我是这样做的:

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();
 }

This seems to work great, until I add some specific HTML in my calendar.这似乎很有效,直到我在日历中添加了一些特定的 HTML。

If I have a '&nbsp' somewhere in my calendar (or similar) the server only gets all the data up to the '&'-point, so I'm assuming the '&' makes it look like anything after this point belongs to a new parameter?如果我的日历(或类似)中有一个 '&nbsp',则服务器只会获取到 '&' 点的所有数据,所以我假设 '&' 使它看起来像这个点之后的任何东西属于新参数?

How can I fix this?我怎样才能解决这个问题?

First install " Microsoft ASP.NET Web API Client " nuget package:首先安装“ Microsoft ASP.NET Web API Client ”nuget包:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:然后使用以下函数发布您的数据:

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>();
        }
    }
}

And this is how to use it:这是如何使用它:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or或者

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

or (not recommended)或(不推荐)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.由于您的内容类型是application/x-www-form-urlencoded您需要对 POST 正文进行编码,特别是如果它包含像&这样的字符&它们在表单中具有特殊含义。

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.在将字符串写入请求流之前,尝试通过HttpUtility.UrlEncode传递您的字符串。

Here are a couple links for reference.这里有几个链接供参考。

As long as the server allows the ampresand character to be POSTed (not all do as it can be unsafe), all you should have to do is URL Encode the character.只要服务器允许 POST 和号字符(并非所有都这样做,因为它可能不安全),您所要做的就是对字符进行 URL 编码。 In the case of an ampresand, you should replace the character with %26 .对于和号,您应该用%26替换该字符。

.NET provides a nice way of encoding the entire string for you though: .NET 为您提供了一种很好的编码整个字符串的方法:

string strNew = "&uploadfile=true&file=" + HttpUtility.UrlEncode(iCalStr);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 C# HttpWebRequest 在 Application/x-www-form-urlencoded 中构造 POST 正文数据的正确方法 - Proper way constructing a POST body data in Application/x-www-form-urlencoded using C# HttpWebRequest C# HttpClient REST 请求使用 Content-Type: application/x-www-form-urlencoded - C# HttpClient REST request using Content-Type: application/x-www-form-urlencoded 如何在内容类型为x-www-form-urlencoded的C#中发布请求? - How to POST request in c# with content-type being x-www-form-urlencoded? 使用内容类型application / x-www-form-urlencoded解析从HTTP POST接收的C#中的JSON数据 - Parsing JSON data in C# received from HTTP POST with content-type application/x-www-form-urlencoded 使用C#获取Webhooks以JSON形式获取内容类型为x-www-form-urlencode的请求消息 - Getting a request message with a content type x-www-form-urlencoded in a form of JSON using C# for webhooks 如何使用 HTTPclient content type = application/x-www-form-urlencoded POST - How to POST using HTTPclient content type = application/x-www-form-urlencoded 如何以Content-Type的形式返回响应:application / x-www-form-urlencoded; 从WCF服务? - How to return response as Content-Type: application/x-www-form-urlencoded; from WCF service? 使用 application/x-www-form-urlencoded 内容类型处理请求,但 NET Core 中的 XML 主体 Web API - Handle Request with application/x-www-form-urlencoded content-type but XML body in NET Core Web API 尝试使用Content-Type application / x-www-form-urlencoded来访问API - Trying to reach API using Content-Type application/x-www-form-urlencoded RestSharp在POST上将Content-Type默认为application / x-www-form-urlencoded - RestSharp defaulting Content-Type to application/x-www-form-urlencoded on POST
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM