如何从.net控制台调用JSON WebService
本文关键字:调用 JSON WebService 控制台 net | 更新日期: 2023-09-27 18:17:51
我正在尝试在c#控制台应用程序中使用JSON web服务。web服务使用HTTP基本身份验证。我无法在控制台应用程序中访问。
代码示例……
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://0000.000.0.000:0000/hrms/rest/login");
request.Method = "POST";
request.ContentType = @"application/json";
//request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("sharads:hrms123"));
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
可以使用HttpClient向JSON Webservice发送HTTP请求。例如
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "yourusername", "yourpwd"))));
HttpResponseMessage reponse = httpClient.GetAsync("api/enumproducts/GetAll").Result;
if (reponse.IsSuccessStatusCode)
{
var enumProducts = reponse.Content.ReadAsAsync<List<EnumProduct>>().Result;
}
HttpClient也支持POST动作。要了解更多细节,您可以查看这篇博客文章