我正在尝试使用C#中的WebRequest对网站执行POST。我发布的网站是一个SMS站点,而messagetext是URL的一部分。为了避免URL中的空格,我正在调用HttpUtility.Encode()来对其进行URL编码。
但是我一直收到URIFormatException - “无效的URI:无法确定URI的格式” - 当我使用类似于此的代码时:
string url = "http://www.stackoverflow.com?question=a sentence with spaces";
string encoded = HttpUtility.UrlEncode(url);
WebRequest r = WebRequest.Create(encoded);
r.Method = "POST";
r.ContentLength = encoded.Length;
WebResponse response = r.GetResponse();
当我调用WebRequest.Create()时会发生异常。
我做错了什么?
答案 0 :(得分:16)
您应该只编码参数,而不是整个网址,所以请尝试:
string url = "http://www.stackoverflow.com?question=" + HttpUtility.UrlEncode("a sentence with spaces");
WebRequest r = WebRequest.Create(url);
r.Method = "POST";
r.ContentLength = encoded.Length;
WebResponse response = r.GetResponse();
编码整个网址意味着://和?也编码。然后,编码的字符串不再是有效的URL。
答案 1 :(得分:1)
UrlEncode只应用于查询字符串。试试这个:
string query = "a sentence with spaces";
string encoded = "http://www.stackoverflow.com/?question=" + HttpUtility.UrlEncode(query);
您的代码的当前版本是对URL中的斜杠和冒号进行urlencoding,这会让webrequest感到困惑。