C# Restful Client



我已经实现了 C# Restful 服务,并且该服务使用此 URL 运行良好:http://port/restfulService.svc/json/?id=SHAKEEL"和浏览器的结果是:您请求的XML产品是:shakel我想在控制台客户端的帮助下使用此服务,为此我实现了以下内容但不起作用,并且 IN 结果它返回,无法发送具有此谓词类型的内容正文,请为我提供建议,这些建议可能会引导我找到解决方案。谢谢。

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");
}

HTTP GET 请求无法发送正文,因此您应该删除以下行:

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

此外,System.Net.WebClient为与Web服务器的基本交互提供了更简单的界面。 从 Web 请求中获取字符串非常简单:

using (WebClient client = new WebClient()) { 
    string result = client.DownloadString("http://port/restfulService.svc/json/id=SHAKEEL");
}

最新更新