i have the following API json request
"myjsonrequest": {
"ServiceKey": "Hello",
"Identityvals": {
"IDName": "regnum",
"IDValue": "112233"
}
}
any simple way to get the response , im using ASP.net c#
i tried this code
HttpClient client = new HttpClient();
string x = "{'IDName','regnum'},{'IDValue','112233'}";
var Keys = new Dictionary<string, string>
{
{ "ServiceKey", "hello" },
{ "PractitionerIdentity",x}
};
var content = new FormUrlEncodedContent(Keys);
var response = await client.PostAsync("https://apiurl", content);
var responseval = await response.Content.ReadAsStringAsync();
Try this :
var json = new {
ServiceKey = "",
PractitionerIdentity = new {
IDName = "" ,
IDValue = ""
}
};
HttpClient client = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json")
var response = await client.PostAsync("https://apiurl", content);
Your Json data should be saved to a model in the following way:
public class YourJsonData{
public string ServiceKey {get; set;}
//add other names
}
The best thing about this is that if you call your object, you get a variable back for easy usage.
then you can add it in a task:
public async Task<List<YourJsonData>> GetJsonAsync(CancellationToken cancellationToken = default)
{
using (var client = new HttpClient())
{
//Make the request, and ensure we can reach it
var response = await client.GetAsync(yourJosnUrl, cancellationToken);
if (response.IsSuccessStatusCode)
{
//Read the actual stream (download the content)
var content = await response.Content.ReadAsStringAsync();
//Make sure we do have some valid content before we try to deserialize it
if (string.IsNullOrEmpty(content))
{
return new List<YourJsonData>();
}
//Deserialize into a list of yourjsondata
return JsonConvert.DeserializeObject<List<YourJsonData>>(content);
}
}
return new List<YourJsonData>();
}
also if you are lazy, you can replace YourJsonData with dynamic. the downpart here is that you won't be able to see what you are revering to.
Related
I'm trying to send a http post request in JSON format which should look like this:
{
"id":"72832",
"name":"John"
}
I have attempted to do it like below but if I am correct this is not sending a request in json format.
var values = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("https://myurl",content);
// code to do something with response
}
How could I modify the code to send the request in json format?
try this
using (var client = new HttpClient())
{
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
var baseAddress = "https://....";
var api = "/controller/action";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(contentType);
var data = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
var jsonData = JsonConvert.SerializeObject(data);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync(api, contentData);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}
Update
If the request comes back with Json data in the form `
{ "return":"8.00", "name":"John" }
you have to create result model
public class ResultModel
{
public string Name {get; set;}
public double Return {get; set;}
}
and code will be
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ResultModel>(stringData);
var value=result.Return;
var name=Result.Name;
}
I would start off by using RestSharp.
dotnet add package RestSharp
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
Just pass in your dictionary as the body object - I would recommend creating a DTOS class to send through though.
Then you can get certain aspects of the RestResponse object that is returned like:
var returnContent = response.Content;
var statusCode = response.StatusCode;
I am attempting to send POST data to my server and get back a response. For some reason, no POST data is actually getting sent. A request is being sent to my server but the POST array is empty.
Here is my code for sending the request:
public class GlobalMethods
{
public async Task<string> callAjax(string mthd,NameValueCollection parameters)
{
var client = new HttpClient();
var content = JsonConvert.SerializeObject(parameters);
var result = await client.PostAsync("http://dev.adex-intl.com/adex/mvc/receiving/"+mthd, new StringContent(content)).ConfigureAwait(false);
var tokenJson = "";
if (result.IsSuccessStatusCode)
{
tokenJson = await result.Content.ReadAsStringAsync();
}
return tokenJson;
}
}
And here is my code that calls the above method:
public void loginPressed(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(badge.Text)) {
DisplayAlert("Error", "Enter your badge number", "Ok");
} else {
IsBusy = true;
NameValueCollection parameters = new NameValueCollection();
parameters["badgetNumber"] = badge.Text;
GlobalMethods globalMethods = new GlobalMethods();
var results = globalMethods.callAjax("login", parameters);
}
}
I'm not sure what I'm doing wrong. Also, I'm a newbie to Xamarin and C# so I'm not even sure if the way I am attempting to do things is the best way.
You haven't specify the type of content that you want to send, in your case it's 'application/json', you can set it like that:
"var client = new HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(parameters));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");". Also, I would suggest you to write code like that:
var uri = new Uri(url);
using (var body = new StringContent(JsonConvert.SerializeObject(data)))
{
body.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var request = new HttpRequestMessage
{
Version = new Version(1, 0),
Content = body,
Method = HttpMethod.Post,
RequestUri = uri
};
try
{
using (var response = await _client.SendAsync(request,cancellationToken))
{
if (response.IsSuccessStatusCode)
{
//Deal with success response
}
else
{
//Deal with non-success response
}
}
}
catch(Exception ex)
{
//Deal with exception.
}
}
You can use PostAsync for async sending data to server. your code should be something like this:
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "p1", "data1" },
{ "p2", "data2" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/index.php", content);
var responseString = await response.Content.ReadAsStringAsync();
I have an object.
I'am sending it this to my api project this way :
mymodel obj = new mymodel();
obj.prop = "this";
obj.prop2 = "prop2";
var content = JsonConvert.SerializeObject(obj);
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string response = "";
using (HttpClient client = new HttpClient())
{
var rez = await client.PostAsync(uri + myenum.Insert, byteContent).ConfigureAwait(false);
response = rez.ToString();
}
In my api method i want to convert that string or http content again to model.
[ActionName("Insert")]
[HttpGet]
public bool Insert(string obj)
{
try
{
mymodel model = JsonConvert.DeserializeObject<mymodel>(obj);
How to handle object i'am sending with postasync in my api method ?
Any help ?
First you cannot use PostAsync on a HTTPGet method.
Second, I dont understand what you mean. If you are using json then you dont have to do anything. Just have a simple client method as such:
public async Task<TResult> PostAsync<TResult, TInput>(string uriString, TInput payload = null) where TInput : class
{
var uri = new Uri(uriString);
using (var client = GetHttpClient())
{
var jsonContent = JsonConvert.SerializeObject(payload, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
HttpResponseMessage response = await client.PostAsync(uri, new StringContent(jsonContent, Encoding.UTF8, "application/json"));
if (response.StatusCode != HttpStatusCode.OK)
{
//Log.Error(response.ReasonPhrase);
return default(TResult);
}
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResult>(json);
}
}
And you can just add the same object to your API like
[ActionName("Insert")]
[HttpPost]
public bool Insert(YourObjectClass obj)
{
try
{
....code....
}
}
I have no idea how to POST JSON with HttpClient. I find some solution, like this, but I have to use HttpClient, cause of async and have to add a header.
This is my code below. Any idea how to fix it?
List<Order> list = new List<Order> { new Order() { Name = "CreatedTime", OrderBy = 1 } };
Queues items = new Queues { Orders = list };
var values = new Dictionary<string, string> { { "Orders", JsonConvert.SerializeObject(list) } };
var content = new FormUrlEncodedContent(values);
//HttpContent cc = new StringContent(JsonConvert.SerializeObject(items));
_msg = await _client.PostAsync(input, content);
//_msg = await _client.PostAsync(input, cc);
var response = await _msg.Content.ReadAsStringAsync();
You can use the method PostAsJsonAsync which can be found in the extensions assemblies:
System.Net.Http.Formatting.dll
Example
public static async Task SendJsonDemo(object content)
{
using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync("https://example.com", content);
}
}
If you want to add custom headers to the request, add it to DefaultRequestHeaders:
client.DefaultRequestHeaders.Add("mycustom", "header1");
You can send any type of request like as
public static async Task<HttpResponseMessage> SendRequest(HttpMethod method, string endPoint, string accessToken, dynamic content = null)
{
HttpResponseMessage response = null;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(method, endPoint))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
if (content != null)
{
string c;
if (content is string)
c = content;
else
c = JsonConvert.SerializeObject(content);
request.Content = new StringContent(c, Encoding.UTF8, "application/json");
}
response = await client.SendAsync(request).ConfigureAwait(false);
}
}
return response;
}
I'm POSTing to API that is returning a 409 response code along with a response body that looks like this:
{
"message": "Exception thrown.",
"errorDescription": "Object does not exist"
}
How can I pull out the Response Body and deserialize it?
I am using HttpClient:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:60129");
var model = new Inspection
{
CategoryId = 1,
InspectionId = 0,
Descriptor1 = "test descriptor 121212",
Name = "my inspection 1121212"
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(model);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var result = client.PostAsync("api/Inspections/UpdateInspection", stringContent);
var r = result.Result;
I seems like such a common thing to do, but I'm struggling to find where the data is in my result.
You can use ReadAsAsync<T> on the content of the response to a concrete type or ReadAsStringAsync to get the raw JSON string.
Would also suggest using Json.Net for working with the JSON.
var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);
var json = await response.Content.ReadAsStringAsync();
A concrete response model can be created
public class ErrorBody {
public string message { get; set; }
public string errorDescription { get; set; }
}
and used to read responses that are not successful.
var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);
if(response.IsSuccessStatusCode) {
//...
} else {
var error = await response.Content.ReadAsAsync<ErrorBody>();
//...do something with error.
}