2011-10-08 29 views
2

我的任務是以XML格式發送請求和接收響應(charset =「windows-1251」)。 當我使用HttpWebRequest和HttpWebResponse類(代碼片段1)時它工作正確。 但RestRequest和RestResponse類(代碼片段2)存在問題。 client.Execute(req)代碼返回的響應爲ErrorException = {「輸入字符串的格式不正確。」}。 我想,問題是RestSharp的類無法識別「windows-1251」編碼。如何強制他們使用「windows-1251」編碼?響應obect類型HttpWebResponse的如何強制RestRequest和RestResponse類使用「windows-1251」編碼?

州:

響應obect類型RestResponse的狀態:

代碼段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(); 
} 

代碼段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請求的10

樣品:

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

回答

0

從文檔here

RequestBody

如果該參數被設置,它的值將被髮送作爲 請求的主體。只有一個RequestBody參數被接受 - 第一個。

該參數的名稱將用作請求的 的Content-Type標頭。

所以:

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