我在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();
}
}
答案 0 :(得分:5)
来自asp.net网站上的documentation。这显示了它是如何在C#中完成的,你尝试使用的RestClient是一个lib,它封装了类似这样的东西。 RestClient可以作为块包添加。
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);
}
}
}
}
}