gpt4 book ai didi

c# - 如何从控制台应用程序调用 REST API?

转载 作者:太空狗 更新时间:2023-10-29 23:58:55 27 4
gpt4 key购买 nike

如何从控制台应用程序调用 REST API?

我的 REST 服务的响应将是 XML 格式。

在网络上我是这样调用的

string url = string.Format("{0}/name?PrimaryName={1}", ConfigurationManager.AppSettings["URLREST"], txtName.Text);
string details= CallRestMethod(url);

public string CallRestMethod(string url)
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "GET";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Username", "xyz");
webrequest.Headers.Add("Password", "abc");
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
return result;
}

我想在控制台应用程序中调用相同的方法。

我该怎么做?

最佳答案

试试这个代码类程序名字空间应该是

using System.Net;
using System.IO;
{
static void Main(string[] args)
{
string url = string.Format("{0}/name?PrimaryName={1}", System.Configuration.ConfigurationManager.AppSettings["URLREST"], "yournmae");
string details = CallRestMethod(url);
}

public static string CallRestMethod(string url)
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "GET";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.Headers.Add("Username", "xyz");
webrequest.Headers.Add("Password", "abc");
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
webresponse.Close();
return result;
}
}

关于c# - 如何从控制台应用程序调用 REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com