我有一个用 JAVA 开发的基于 REST 的 API。现在我试图从基于控制台的 C# 应用程序调用该 API,即从它的主要功能。我想知道是否可以这样做。 我已经尝试了一些但它不起作用
//我在我的类文件中写了下面的代码。但是我找不到 RestClient 类。我需要包括什么
static void Main(string[] args)
{
{
string endPoint = @"http:\\myRestService.com\api\";
var client = new RestClient(endPoint);
var json = client.MakeRequest();
}
}
最佳答案
来自documentation在 asp.net 网站上。这显示了它是如何在 C# 中完成的,您尝试使用的 RestClient 是一个库,它封装了类似此示例的内容。 RestClient 可以作为 block 包添加。
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ProductStoreClient
{
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
Uri gizmoUrl = response.Headers.Location;
// HTTP PUT
gizmo.Price = 80; // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
// HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);
}
}
}
}
}
关于c# - 从 C# 调用 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469235/