我已经实施了C#Restful Service,并且使用此URL服务正常运行: HTP://port/restfulService.svc/json/ ID =沙基尔” 和浏览器中的结果是: 您所请求的XML产品是:shakeel 我希望在Console Client的帮助下使用此服务,因为我实现了以下但不能正常工作,并且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");
}
答案 0 :(得分:2)
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");
}