我是初学者,正在创建winform应用程序。在其中我必须使用API进行简单CRUD操作。我的客户与我共享了API,并要求以JSON形式发送数据。
API:http : //blabla.com/blabla/api/login-valida
关键字:“ HelloWorld”
值:{“电子邮件”:“ user@gmail.com”,“密码”:“ 123456”,“时间”:“ 2015-09-22 10:15:20”}
响应:Login_id
如何将数据转换为JSON,如何使用POST方法调用API并获得响应?
编辑 在stackoverflow上的某个地方我找到了这个解决方案
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)未找到。”
您可以看一下以下文档教程:
但是,作为答案,我将在此处分享一个简短的分步指南,介绍如何以Windows形式调用和使用Web API:
Microsoft.AspNet.WebApi.Client
打开工具菜单→NuGet程序包管理器→程序包管理器控制台→在程序包管理器控制台窗口中,键入以下命令:
Install-Package Microsoft.AspNet.WebApi.Client
您可以通过右键单击项目并选择“管理NuGet软件包”来安装软件包。
设置HttpClient- 创建的实例HttpClient并设置其BaseAddress和DefaultRequestHeaders。例如:
HttpClient
BaseAddress
DefaultRequestHeaders
// 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”));
发送请求 -要发送请求,可以使用以下方法HttpClient:
GetAsync
GetStringAsync``GetByteArrayAsync``GetStreamAsync
PostAsync``PostAsJsonAsync``PostAsXmlAsync
PutAsync``PutAsJsonAsync``PutAsXmlAsync
DeleteAsync
Send
注意: 请记住,要为这些方法设置请求的URL,因为在定义时已指定了基本URL client,则此处为这些方法设置了路径,路由值和查询字符串,例如:
client
// 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内容,则可以轻松地使用package JsonConvert类对其Newtonsoft.Json进行解析。例如:
GetStringAsync
JsonConvert
Newtonsoft.Json
// 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与你有HttpResponseMessage那么你可以使用ReadAsAsync,ReadAsByteArrayAsync,ReadAsStreamAsync,`ReadAsStringAsync,例如:
PostAsJsonAsync
HttpResponseMessage
ReadAsAsync
ReadAsByteArrayAsync
ReadAsStreamAsync
// 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;
性能提示
设计技巧
IProductServieClient
ProductWebAPIClientService