问题描述
我正在用 C# 编写一个连接 API 的小型应用程序.
I'm writing a small API-connected application in C#.
我连接到一个 API,该 API 的方法接受一个长字符串,即日历(ics)文件的内容.
I connect to a API which has a method that takes a long string, the contents of a calendar(ics) file.
我是这样做的:
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();
}
这似乎很好用,直到我在日历中添加了一些特定的 HTML.
This seems to work great, until I add some specific HTML in my calendar.
如果我的日历(或类似)中有 ",则服务器只会获取&"点之前的所有数据,因此我假设&"让它看起来像这个点之后的任何东西都属于一个新的参数?
If I have a ' ' 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?
我该如何解决这个问题?
How can I fix this?
推荐答案
由于你的内容类型是 application/x-www-form-urlencoded
你需要对 POST 正文进行编码,尤其是如果它包含像 &
这样的字符,它们在表单中具有特殊含义.
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.
在编写之前尝试通过 HttpUtility.UrlEncode 传递您的字符串到请求流.
Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.
这里有几个链接供参考.
Here are a couple links for reference.
这篇关于类型为“application/x-www-form-urlencoded"的 C# HttpWebRequest;- 如何发送“&"内容正文中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!