1

我已经实现了 C# Restful 服务,并且该服务运行良好,使用以下 URL:htp://port/restfulService.svc/json/?id=SHAKEEL" 并且浏览器中的结果是:您请求的 XML 产品是 :shakeel 我想使用此服务在控制台客户端的帮助下,因为我实现了以下但无法正常工作,并且结果返回, 无法发送具有此动词类型的内容主体,请向我提供可能导致我解决方案的建议。谢谢。

static void Main(string[] args)
{
    do
    {
        try
        {
            string uri = "http://port/restfulService.svc/json/id=SHAKEEL";
            HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
            req.KeepAlive = false;
            req.ContentLength = 0;
            req.ContentType = "text/xml";
            Stream data = req.GetRequestStream();
            data.Close();

            string result;
            using (WebResponse resp = req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
            }
            result = result.Substring(1, result.Length - 2);
            Console.WriteLine(result);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
        Console.WriteLine();
        Console.WriteLine("Do you want to continue?");
    } while (Console.ReadLine() == "Y");
}
4

1 回答 1

2

HTTP GET 请求不能发送正文,因此您应该删除这些行:

req.ContentLength = 0;
req.ContentType = "text/xml";
Stream data = req.GetRequestStream();
data.Close();

此外,System.Net.WebClient为与 Web 服务器的基本交互提供了一个更简单的接口。从 webrequest 中获取字符串非常简单:

using (WebClient client = new WebClient()) { 
    string result = client.DownloadString("http://port/restfulService.svc/json/id=SHAKEEL");
}
于 2013-09-12T11:46:44.483 回答