I have a API in C# and another one in Visual Basic. I need to send some information in JSON format from the API in C# to the API in Visual Basic, hopefully using POST verb. The context of the situation is like this. A mobile application send information to the API in C#, the API save the data in a database located in the server, then if the information is correct the API in C# have to send the data to the Visual Basic API and save it in other server. Anybody knows hoy to send the data from C# to Visual Basic? Thanks.
It doesn't matter that one API is in C# and the other in VB. As long as the json you are sending is valid (try validating the json you send at jsonlint.com) and can be mapped to an object the API accepts everything should be fine.
It seems like the endpoint api is not accepting the request.
This is my C# code
try
{
var request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
var1 = "example1",
var2 = "example2"
});
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return Request.CreateResponse(HttpStatusCode.OK, new { Respuesta = result }, "application/json");
}
}
catch(Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, new { Respuesta = e.ToString() }, "application/json");
}
}
And this is my function in Visual Basic
Public Function PostValue(ByVal json as String)
return json
End Function
Thats all. And throw me this error
{
"Respuesta": "System.Net.WebException: The remote server returned an error: (404) Not Found.\r\n at System.Net.HttpWebRequest.GetResponse()\r\n at Servicios.Controllers.SAPEnviarFacturasController.SAPEnviarFacturas() in C:\TFS\Servicios\Controllers\SAPEnviarFacturasController.cs:line 44"
}
I have fetch channel history in my .Net Web API.
The slack reference https://api.slack.com/methods/channels.history it states that we need to post the request.
Please if someone could help me with the code.
Part of Code I have implemented:
#region create json payload to send to slack
GetLatestMessage payload = new GetLatestMessage()
{
channel = "###",//value.channel_name,
token = "############################"//added the token i have generated
// user_name = value.user_name,
//text = value.text
};
#endregion
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}
I figured out the issue I was facing.I was trying to sent the post json data in to Slack url. However The Slack Web API doesn't accept JSON data.Now when I post data using standard HTTP form attributes it accepts and returns proper response.
New code:
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", new NameValueCollection() {
{"token","###################"},
{"channel","######"}});
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}
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": "user#gmail.com","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."
You can take a look at the following docs tutorial:
Call a Web API From a .NET Client
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.Client NuGet 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 HttpClient and set up its BaseAddress and DefaultRequestHeaders. 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 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 use JsonConvert class of Newtonsoft.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;
If you have used methods like GetAsync or PostAsJsonAsync and you have an HttpResponseMessage then you can use ReadAsAsync, 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
HttpClient is 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 IProductServieClient interface, then as an implementation put all the WEB API logic inside the ProductWebAPIClientService which you implement to contain codes to interact with WEB API. Your application should rely on IProductServieClient. (SOLID Principles, Dependency Inversion).
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;
}
Use Json.Net to convert data into JSON
Use WebClient to POST data
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);
Here is another example using an online REST service (https://northwind.vercel.app) which allows interaction with Northwind API.
This example uses HttpClient and JsonConvert to get or post data. Here is a very quick example:
Install Newtonsoft.Json nuget package. And add the following using statements to your form:
using System.Net.Http;
using Newtonsoft.Json
Define an instance of the HttpClient, at class level:
private static HttpClient client = new HttpClient();
To send a GET request, for example getting list of all data:
var url = "https://northwind.vercel.app/api/categories";
var response = await client.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var content = await response.Content.ReadAsStringAsync();
var categories = JsonConvert.DeserializeObject<List<Category>>(content);
dataGridView1.DataSource = categories;
}
You can also use other overloads of Get, like GetStringAsync, GetStreamAsync, and etc. But GetAsync is a more generic method allowing you to get the status code as well.
To send a POST request, for example posting a new data:
var url = "https://northwind.vercel.app/api/categories";
var data = new Category() { Name = "Lorem", Description = "Ipsum" };
var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var requestContent = new StringContent(jsonData, Encoding.Unicode, "application/json");
var response = await client.PostAsync(url, requestContent);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
{
var content = await response.Content.ReadAsStringAsync();
var createdCategory = JsonConvert.DeserializeObject<Category>(content);
MessageBox.Show(createdCategory.Id.ToString())
}
To learn more and see some best practices or see an example without JsonConvert, see my other post.
I'm building a client-server desktop app in C# and RestSharp seems to be tripping my program up somewhere. The oddest thing is that other POSTs are working to the same Node.js server app.
Here's my code using RestSharp:
RestClient client = new RestClient("http://"+Configuration.server);
RestRequest request = new RestRequest("sync", Method.POST);
request.AddParameter("added", Indexer.getAddedJson());
request.AddParameter("removed", Indexer.getRemovedJson());
RestResponse<StatusResponse> response = (RestResponse<StatusResponse>)client.Execute<StatusResponse>(request);
e.Result = response.Data;
This doesn't work - and by that I mean it doesn't make a call to the server at all. I've verified this using Fiddler too.
But this does work:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["added"] = Indexer.getAddedJson();
data["removed"] = Indexer.getRemovedJson();
var resp = wb.UploadValues("http://" + Configuration.server + "/sync", "POST", data);
}
I can't figure out for the life of me what's going on. I don't want to stop using RestSharp just for this request, other POST requests are working just fine!
It's not a deserialization problem, because response.Content is null. I'm getting a StatusResponse in the other calls as well so this is probably not the issue.
Ok, I'm assuming that this is an easy one, but I can't find my answer anywhere... I have a client that needs to query a rest api through .net. He sent me the url for the api, and a sample of the data. This is what he sent:
<?xml version="1.0"?>
<root>
<request>
<APIClientID>0</APIClientID >
<Version>0</Version>
<APIPassword>password</APIPassword >
<Function>functionName</Function >
<Params>
<UserId>(current-datetime)</UserId >
<page>example.aspx</page>
<application>appName</application>
<function>functionName</function>
</Params>
</request >
</root >
I'm using restsharp and I'm trying to do a post to the service. But I keep just getting back the get page with the details for the api. This is what I'm doing with restsharp...
var client = new RestClient();
client.BaseUrl = url;
var request = new RestRequest(Method.POST);
request.AddHeader("APIClientID", "4");
request.AddHeader("Version", "0");
request.AddHeader("APIPassword", "password");
request.AddHeader("Function", "TransAPIStats");
request.AddHeader("Version", "0");
request.AddParameter("Client", "test client");
request.AddParameter("UserId", DateTime.Now.ToString());
request.AddParameter("Page", "example.aspx");
request.AddParameter("Application", "app");
request.AddParameter("Function", "function");
RestResponse response = client.Execute(request);
any thoughts on where I'm going wrong would be greatly apprecaited! I'm guessing that there is something about hte xml that I'm not translating properly to the restsharp call, but I'm lost at this point... thanks!
If the POST body needs to be an XML document, use AddBody(). It defaults to serializing the object passed to it as XML. You could do this with an anonymous object that matches the schema you're trying to generate:
var client = new RestClient();
client.BaseUrl = url;
var request = new RestRequest(Method.POST);
request.AddBody(new {
root = new {
request = new {
APIClientID = 4,
Version = 0,
APIPassword = "password",
Function = "TransAPIStats",
Params = new {
UserId = "abc",
page = "example.aspx",
Application = "hrblock-cb",
Function = "ecb"
}
}
}
});
Or you could define a simple C# object that matches the schema and use that instead of the inline anonymous object.
If you need control over the serialization (the default should work based on the example data you show), you can implement your own ISerializer. Docs for that are the last section here: https://github.com/restsharp/RestSharp/wiki/Deserialization