KorVet
KorVet

Reputation: 63

How to force RestRequest and RestResponse classes use "windows-1251" encoding?

My task is to send request and receive response in XML format (charset = "windows-1251"). It works correct when I use HttpWebRequest and HttpWebResponse classes (code snippet 1). But there is an issue with the RestRequest and RestResponse classes (code snippet 2). The client.Execute(req) code returns response with ErrorException = {"Input string was not in a correct format."}. I suppose, problem is that RestSharp's classes cannot recognize "windows-1251" encoding. How to force them use "windows-1251" encoding?

State of the response obect type of HttpWebResponse:

State of the response obect type of RestResponse:

Code snippet 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();
}

Code snippet 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;
}

Sample of the XML request:

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

Upvotes: 2

Views: 1794

Answers (1)

Morphed
Morphed

Reputation: 3619

From the documentation here

RequestBody

If this parameter is set, its value will be sent as the body of the request. Only one RequestBody Parameter is accepted – the first one.

The name of the parameter will be used as the Content-Type header for the request.

So:

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

Upvotes: 0

Related Questions