使用C#.net调用和使用Winform中的Web API [英] Call and consume Web API in winform using C#.net
问题描述
我是初学者,正在创建winform应用程序.我必须在其中使用API进行简单CRUD操作.我的客户与我共享了API,并要求以JSON形式发送数据.
I am beginner and creating winform application. In which i have to use API for Simple CRUD operation. My client had shared API with me and asked to send data in form of JSON.
API: http://blabla.com/blabla/api/login-valida
KEY:"HelloWorld"
KEY : "HelloWorld"
值:{电子邮件":"user@gmail.com",密码":"123456",时间":"2015-09-22 10:15:20"}
Value : { "email": "user@gmail.com","password": "123456","time": "2015-09-22 10:15:20"}
响应:Login_id
Response : Login_id
如何将数据转换为JSON,如何使用POST方法调用API并获得响应?
How can i convert data to JSON, call API using POST method and get response?
编辑 我在stackoverflow的某个地方找到了这个解决方案
EDIT Somewhere on stackoverflow i found this solution
public static void POST(string url, string jsonContent)
{
url="blabla.com/api/blala" + url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = @"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch
{
throw;
}
}
//on my login button click
private void btnLogin_Click(object sender, EventArgs e)
{
CallAPI.POST("login-validate", "{ \"email\":" + txtUserName.Text + " ,\"password\":" + txtPassword.Text + ",\"time\": " + DateTime.Now.ToString("yyyy-MM-dd h:mm tt") + "}");
}
我遇到了一个异常,说远程服务器返回了一个错误:(404)未找到."
I got exception that says "The remote server returned an error: (404) Not Found."
推荐答案
您可以查看以下文档教程:
You can take a look at the following docs tutorial:
- 但是,作为答案,我将在这里分享一个简短的分步指南,介绍如何以Windows形式调用和使用Web API:
But as an answer, here I will share a quick and short a step by step guide about how to call and consume web API in Windows forms:
-
安装软件包-安装
Microsoft.AspNet.WebApi.Client
NuGet程序包(Web API客户端库).
Install Package - Install the
Microsoft.AspNet.WebApi.Client
NuGet package (Web API Client Libraries).
打开工具菜单→NuGet软件包管理器→软件包管理器控制台→在软件包管理器控制台"窗口中,键入以下命令:
Open Tools menu → NuGet Package Manager → Package Manager Console → In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Client
您可以通过右键单击项目并选择管理NuGet软件包"来安装软件包.
You can install package by right click on project and choosing Manage NuGet Packages as well.
设置HttpClient -创建
BaseAddress
和DefaultRequestHeaders
.例如:Set up HttpClient - Create an instance of
HttpClient
and set up itsBaseAddress
andDefaultRequestHeaders
. For example:// In the class static HttpClient client = new HttpClient(); // Put the following code where you want to initialize the class // It can be the static constructor or a one-time initializer client.BaseAddress = new Uri("http://localhost:4354/api/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
-
Send Request - To send the requests, you can use the following methods of the
HttpClient
:- 获取:
GetAsync
,GetStringAsync
,GetByteArrayAsync
,GetStreamAsync
- POST:
PostAsync
,PostAsJsonAsync
,PostAsXmlAsync
- 输入:
PutAsync
,PutAsJsonAsync
,PutAsXmlAsync
- 删除:
DeleteAsync
- 另一种HTTP方法:
Send
- GET:
GetAsync
,GetStringAsync
,GetByteArrayAsync
,GetStreamAsync
- POST:
PostAsync
,PostAsJsonAsync
,PostAsXmlAsync
- PUT:
PutAsync
,PutAsJsonAsync
,PutAsXmlAsync
- DELETE:
DeleteAsync
- Another HTTP method:
Send
注意:请记住,要设置方法请求的URL,因为在定义client
时已指定了基本URL,所以在这里为这些方法传递路径,路由值和查询字符串,例如:
Note: To set the URL of the request for the methods, keep in mind, since you have specified the base URL when you defined theclient
, then here for these methods, just pass path, route values and query strings, for example:// Assuming http://localhost:4354/api/ as BaseAddress var response = await client.GetAsync("products");
或
// Assuming http://localhost:4354/api/ as BaseAddress var product = new Product() { Name = "P1", Price = 100, Category = "C1" }; var response = await client.PostAsJsonAsync("products", product);
- 获取:
-
获取答复
要获得响应,如果您使用了
GetStringAsync
之类的方法,则将响应作为字符串使用就足以解析响应.如果响应是您知道的Json内容,则可以轻松使用 <<的JsonConvert
类c20> 包进行解析.例如:To get the response, if you have used methods like
GetStringAsync
, then you have the response as string and it's enough to parse the response. If the response is a Json content which you know, you can easily useJsonConvert
class ofNewtonsoft.Json
package to parse it. For example:// Assuming http://localhost:4354/api/ as BaseAddress var response = await client.GetStringAsync("product"); var data = JsonConvert.DeserializeObject<List<Product>>(response); this.productBindingSource.DataSource = data;
如果您使用过
GetAsync
或PostAsJsonAsync
之类的方法,并且具有If you have used methods like
GetAsync
orPostAsJsonAsync
and you have anHttpResponseMessage
then you can useReadAsAsync
,ReadAsByteArrayAsync
,ReadAsStreamAsync
, `ReadAsStringAsync, for example:// Assuming http://localhost:4354/api/ as BaseAddress var response = await client.GetAsync("products"); var data = await response.Content.ReadAsAsync<IEnumerable<Product>>(); this.productBindingSource.DataSource = data;
-
HttpClient
是一种类型,只能创建一次然后共享.因此,不要在每次要使用它时都将其放入using块中.而是,创建类的实例并通过静态成员共享它.要了解有关此内容的更多信息,请查看不正确的实例化反模式 - 尝试避免将与Web API相关的代码与您的应用程序逻辑混合在一起.例如,假设您有一个产品Web API服务.然后要使用它,首先定义一个
IProductServieClient
接口,然后作为实现将所有WEB API逻辑放入ProductWebAPIClientService
内,您可以实现该逻辑以包含与WEB API交互的代码.您的应用程序应依赖IProductServieClient
. (SOLID原则,依赖倒置). - Try to avoid mixing the Web API related code with your application logic. For example let's say you have a product Web API service. Then to use it, first define an
IProductServieClient
interface, then as an implementation put all the WEB API logic inside theProductWebAPIClientService
which you implement to contain codes to interact with WEB API. Your application should rely onIProductServieClient
. (SOLID Principles, Dependency Inversion).
性能提示
设计技巧
这篇关于使用C#.net调用和使用Winform中的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!