【问题标题】:C# Restful ClientC# Restful 客户端
【发布时间】:2013-09-16 18:38:58
【问题描述】:

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

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

【问题讨论】:

标签: c# rest console client wcf-rest


【解决方案1】:

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

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

此外,System.Net.WebClient 为与网络服务器的基本交互提供了更简单的界面。从 webrequest 中获取字符串很简单:

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

【讨论】:

  • 亲爱的,我的问题已经解决了,但如果你能分享,我想知道更多细节,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2016-07-17
  • 2023-03-13
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多