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”
Value : { “email”: “[email protected]“,”password”: “123456”,”time”: “2015-09-22 10:15:20”}
Response : Login_id
How can i convert data to JSON, call API using POST method and get response?
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") + "}");
}
I got exception that says “The remote server returned an error: (404) Not Found.”
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can take a look at the following docs tutorial:
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:
-
Install Package – Install the
Microsoft.AspNet.WebApi.ClientNuGet package (Web API Client Libraries).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
You can install package by right click on project and choosing Manage NuGet Packages as well.
-
Set up HttpClient – Create an instance of
HttpClientand set up itsBaseAddressandDefaultRequestHeaders. 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:- GET:
GetAsync,GetStringAsync,GetByteArrayAsync,GetStreamAsync - POST:
PostAsync,PostAsJsonAsync,PostAsXmlAsync - PUT:
PutAsync,PutAsJsonAsync,PutAsXmlAsync - DELETE:
DeleteAsync - Another HTTP method:
Send
Note: To set the URL of the request for the methods, keep in mind, since you have specified the base URL when you defined the
client, 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");or
// Assuming http://localhost:4354/api/ as BaseAddress var product = new Product() { Name = "P1", Price = 100, Category = "C1" }; var response = await client.PostAsJsonAsync("products", product); - GET:
-
Get the Response
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 useJsonConvertclass ofNewtonsoft.Jsonpackage 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;If you have used methods like
GetAsyncorPostAsJsonAsyncand you have anHttpResponseMessagethen 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;
Performance Tip
HttpClientis a type that is meant to be created once and then shared. So don’t try to put it in a using block every time that you want to use it. Instead, create an instance of the class and share it through a static member. To read more about this, take a look at Improper Instantiation antipattern
Design Tip
- 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
IProductServieClientinterface, then as an implementation put all the WEB API logic inside theProductWebAPIClientServicewhich you implement to contain codes to interact with WEB API. Your application should rely onIProductServieClient. (SOLID Principles, Dependency Inversion).
Method 2
Just use the following library.
https://www.nuget.org/packages/RestSharp
GitHub Project: https://github.com/restsharp/RestSharp
Sample Code::
public Customer GetCustomerDetailsByCustomerId(int id)
{
var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
var request = new RestRequest(Method.GET);
request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
dynamic json = JsonConvert.DeserializeObject(content);
JObject customerObjJson = json.CustomerObj;
var customerObj = customerObjJson.ToObject<Customer>();
return customerObj;
}
Method 3
Method 4
Use This code:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.mywebsite.com");
var request = new HttpRequestMessage(HttpMethod.Post, "/path/to/post/to");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("site", "http://www.google.com"));
keyValues.Add(new KeyValuePair<string, string>("content", "This is some content"));
request.Content = new FormUrlEncodedContent(keyValues);
var response = await client.SendAsync(request);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0