发布到休息服务时发出问题

时间:2012-01-20 16:53:54

标签: c# rest

我尝试用restsharp做这个,但没有运气......所以我正在尝试向其他网络服务发帖子。我得到了以下样本xml:

<?xml version="1.0"?>
<root>
<request>
<APIClientID>0</APIClientID >
<Version>0</Version>
<APIPassword>password</APIPassword >
<Function>functionName</Function >
<Params>
<UserId>(current-datetime)</UserId >
<page>example.aspx</page>
<application>appName</application>
<function>functionName</function>
</Params>
</request >
</root >

我正在尝试发布的代码是:

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "POST";
        request.ContentType = "text/xml";

        byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestXML);

        request.ContentLength = byteData.Length;

        // Write data  
        using (Stream postStream = request.GetRequestStream())
        {
            postStream.Write(byteData, 0, byteData.Length);
        }

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        StreamReader reader = new StreamReader(response.GetResponseStream());

        string responseString = reader.ReadToEnd();

但是,每次我尝试发布帖子时,我都会回复来自服务的通用获取响应。对我可能做错的任何帮助都将不胜感激。谢谢!

我想这可能有助于发布我从服务上获得的xml ...

<Function>TransAPIStats</Function>
<Method>
<post>
<Description>Post api statistics to the DB via the API.</Description>
<Params>
<Client>
<Required>true</Required>
<Description>String</Description>
</Client>
<Page>
<Required>true</Required>
<Description>Integer</Description>
</Page>
<Application>
<Required>true</Required>
<Description>String</Description>
</Application>
<Function>
<Required>true</Required>
<Description>String</Description>
</Function>
</Params>
<Return>
<Result>String</Result>
<Status>String</Status>
<Description>String</Description>
</Return>
</post>
</Method>

我尝试改变我给我的样本xml以匹配api xml中列出的参数,但它仍然只是做同样的事情。我有一种感觉,这就是我的问题所在,但它似乎并不想工作......

1 个答案:

答案 0 :(得分:0)

试试这个;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/xml";

using (var postStream = new StreamWriter(request.GetRequestStream()))
{
    postStream.Write(requestXML);
}

string responseString = null;
using (var response = (HttpWebResponse)request.GetResponse())
using (var dataStream = response.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
    responseString = reader.ReadToEnd();
}