【问题标题】:How to force RestRequest and RestResponse classes use "windows-1251" encoding?如何强制 RestRequest 和 RestResponse 类使用“windows-1251”编码?
【发布时间】:2011-10-08 15:42:30
【问题描述】:

我的任务是以 XML 格式(charset = "windows-1251")发送请求和接收响应。 当我使用 HttpWebRequest 和 HttpWebResponse 类(代码 sn-p 1)时,它可以正常工作。 但是 RestRequest 和 RestResponse 类(代码 sn-p 2)存在问题。 client.Execute(req) 代码返回响应并带有 ErrorException = {"Input string was not in a correct format."}. 我想,问题是 RestSharp 的类无法识别“windows-1251”编码。如何强制他们使用“windows-1251”编码?

HttpWebResponse 响应对象类型的状态:

RestResponse 响应对象类型的状态:

代码 sn-p 1:

byte[] bytes = Encoding.GetEncoding(1251).GetBytes(xml);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1251));
    resultXML = sr.ReadToEnd();
    sr.Close();
}

代码 sn-p 2:

private T ExecuteRequest<T>(string resource, RestSharp.Method httpMethod, 
    string bodyXML = null) where T : new()
{
    RestClient client = new RestClient(this.BaseUrl);
    RestRequest req = new RestRequest(resource, httpMethod);
    req.AddParameter("text/xml", bodyXML, ParameterType.RequestBody);
    RestResponse<T> resp = client.Execute<T>(req);
    return resp.Data;
}

XML 请求示例:

<?xml version="1.0" encoding="windows-1251"?>
<digiseller.request>
  <id_seller>1</id_seller>
  <order></order>
</digiseller.request>

【问题讨论】:

    标签: .net asp.net restsharp


    【解决方案1】:

    来自文档here

    请求正文

    如果设置了这个参数,它的值将作为正文发送 要求。只接受一个 RequestBody 参数——第一个。

    参数名称将用作 Content-Type 标头 请求。

    所以:

    request.AddParameter(new Parameter
    {
        Name = "text/xml; charset=windows-1251",
        Type = ParameterType.RequestBody,
        Value = bodyXML
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      相关资源
      最近更新 更多