【问题标题】:httpwebrequest encoding errorhttpwebrequest 编码错误
【发布时间】:2012-10-31 19:49:19
【问题描述】:

我的 httpwebrequests 有时会出现奇怪的错误。

我得到错误:

ArgumentException was unhandled by user code
'' is not a supported encoding name.

我正在运行的代码:

            try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Timeout = 3000;
            request.ReadWriteTimeout = 3000;
            request.Proxy = new WebProxy(p.ToString(), true);

            response = (HttpWebResponse)request.GetResponse();
            Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet);
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), responseEncoding))
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // do stuff
                }
            }


        }
        catch (WebException wexc1)
        {
            if (wexc1.Status == WebExceptionStatus.ProtocolError)
            {
                return false;
            }

        }
        finally
        {
            if (response != null)
                response.Close();
        }

它并没有像 500 个请求中的 1 个那样一直发生。感觉代码无法确定实际的编码..但是我将如何处理呢?

当前错误导致应用程序崩溃

【问题讨论】:

    标签: c# httpwebrequest


    【解决方案1】:

    我假设该行中抛出了异常:

    Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet);
    

    作为一个快速建议,我建议将Encoding.UTF8 或response.ContentEncoding 设置为流的编码,而不是依赖response.CharacterSet()。

    CharacterSet 是一个 WebName(例如 Encoding.UTF8.WebName),而不是编码的专有名称。

    【讨论】:

      【解决方案2】:

      您是否明确设置了请求的编码?像

      Response.Charset = "windows-1252";
      

      在 WebRequest 访问的页面中?如果 Web 服务器没有明确设置 CharacterSet,则它并不总是一致的。

      您还可以检查 CharacterSet 为空的情况并替换为默认值,可能是“windows-1252”或任何适合您的 Web 服务器的编码。示例:

      string charset = response.CharacterSet; 
      if charset == "")
      {
          charset = "windows-1252";
      }
      Encoding responseEncoding = Encoding.GetEncoding(charset);
      

      【讨论】:

        【解决方案3】:

        对我来说,它有效

            private string GetHtmlFromResponse(HttpWebResponse response)
            {
                string sFicha = null;
                using (Stream s = response.GetResponseStream())
                {
                    Encoding eCodificacion = Encoding.GetEncoding(response.CharacterSet);
                    StreamReader sr = new StreamReader(s, eCodificacion);
                    sFicha = sr.ReadToEnd();
                    sr.Close();
                }
        
                return sFicha;
            }
        

        我正在下载一个西班牙语页面,但字符 á、é、í、ó、ú、ñ 丢失了。使用此代码,我得到了正确的文本。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-15
          • 2010-11-06
          • 2013-12-20
          • 2011-01-05
          • 2015-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多