【问题标题】:"The format of the URI could not be determined" with WebRequest“无法确定 URI 的格式”与 WebRequest
【发布时间】:2009-05-25 14:27:52
【问题描述】:

我正在尝试使用 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() 时发生异常。

我做错了什么?

【问题讨论】:

    标签: c# exception httpwebrequest


    【解决方案1】:

    你应该只编码参数,而不是整个 url,所以试试:

    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 进行编码意味着 :// 和 ?也得到编码。编码后的字符串不再是有效的 url。

    【讨论】:

    • this SO post 中所述,最好使用Uri.EscapeDataString() 而不是HttpUtilityServer 方法。
    【解决方案2】:

    UrlEncode 只能用于查询字符串。试试这个:

    string query = "a sentence with spaces";
    string encoded = "http://www.stackoverflow.com/?question=" + HttpUtility.UrlEncode(query);
    

    您的代码的当前版本正在对 URL 中的斜杠和冒号进行 urlencoding,这会混淆 webrequest。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2013-12-15
      • 1970-01-01
      相关资源
      最近更新 更多