I have the following code:
static async Task checkIMEI( double IMEI)
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://kelpom-imei-checker1.p.rapidapi.com/api?service=model&imei=" + IMEI.ToString() ),
Headers =
{
{ "X-RapidAPI-Host", "kelpom-imei-checker1.p.rapidapi.com" },
{ "X-RapidAPI-Key", "key" },
}
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
object result = await response.Content.ReadAsStringAsync();
MessageBox.Show("\n" + result);
}
}
Running this code I get the following
response
I would like to further break up this response and the individual data and assign it to a variable such as
string ModelNum= model_nb >> should show "SM-G891A"
String Brand = brand >> should show "Samsung Korea"
Your help would be appriciated.
first your Client is bad practice use this link HttpClientFactory Microsoft docs to refactor your client.
Then Create Class for your needed model for ex:
public class Mobile
{
public string ModelNum { get; set; }
public string Brand { get; set; }
}
then you should deserialize your result to your model:
var result = await response.Content.ReadAsStringAsync();
var model = JsonSerializer.Deserialize<Mobile>(result);
Related
I'm a Unity developer tool and i want to post a GraphQL request with using System.Net.Http; (i don't want to use the GraphQL dll because there are compatibility problems).
But i have this error (got on the Debug.Log) :
POST body missing, invalid Content-Type, or JSON object has no keys.
My code :
static async Task<string> getEntityID(string path)
{
var values = new Dictionary<string, string>
{
{ "query", "query {topLevelEntityTypes {id}}" },
{ "variables", "{}" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://localhost:4000/graphql", content);
var responseString = await response.Content.ReadAsStringAsync();
Debug.Log(responseString);
return responseString;
}
Thank you !
Solution by ProgrammingLlama :
static async Task<string> getEntityID(string path)
{
var myObject = new QueryJson();
myObject.query = "query {topLevelEntityTypes {id}}";
myObject.variables = "{}";
var response = await client.PostAsync("http://localhost:4000/graphql", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(myObject), Encoding.UTF8, "application/json"));
var responseString = await response.Content.ReadAsStringAsync();
Debug.Log(responseString);
return responseString;
}
Class json
internal class QueryJson
{
public string query { get; set; }
public string variables { get; set; }
}
I have a code where I am creating an instance of HttpClient, which is inside of a foreach loop. Which means it is creating a new instance for each time the iteration takes place. Here is my code :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Net.Mime;
using System.Net.Http.Json;
public class Program
{
static async Task Main(string[] args)
{
//JSON String
string json = #"{
'Values': [
{
'MsgSource': null,
'TagName': 'Data.New_MSG',
'RawValue': '[\r\n {\r\n \'ID\': 145,\r\n \'StationNo\': 6,\r\n
\'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n
\'ControllerAddress\': 2,\r\n \'ProgramNo\': 2,\r\n
\'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-
27T23:30:02\',\r\n \'Description\': \'Irrigation
Completed\',\r\n \'MessageCode\': 5\r\n,\r\n
\'ControllerName\': \'P25-SC-0233\' },\r\n {\r\n \'ID\':
144,\r\n \'StationNo\': 18,\r\n \'RunTime\': 1800,\r\n
\'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n
\'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n
\'EventDate\': \'2022-04-27T22:00:00\',\r\n \'Description\':
\'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n,\r\n
\'ControllerName\': \'P25-SC-0226\' }\r\n]',
'Status': 'Normal',
'ComStatus': null,
'TimeStamp': '2022-04-28 13:17:39.851'
}
]
}";
//Deserializing JSON String
Root root = JsonConvert.DeserializeObject<Root>(json);
//Extracting the value of only RawValue key from the String
string rawValue = root.Values[0].RawValue;
//Creating List of ControllerName key
List<Station> stations = JsonConvert.DeserializeObject<List<Station>>(rawValue);
JArray array = JArray.Parse(rawValue);
int i = 0; //Initializing Index to add ControllerName to the URL in Get http
//request below
foreach(var item in array) //Iterating through array
{
var inc_val = i++;
using (var client = new HttpClient()) //Here I've Instantiated HttpClient
{
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic","auth_value"); //Basic Auth
//Mandatory key for Message body in Post request
string isoTime = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
//Concatenating ControllerName in URL and making get request
HttpResponseMessage get_response = await
client.GetAsync("https://myurl.com/"+stations[inc_val]);
var get_responseString = await get_response.Content.ReadAsStringAsync();
JObject obj = JObject.Parse(get_responseString);
//Extracting id from the response of Get request which has to be used in
//Post Data when making Post request
string name = (string) obj["managedObject"]["id"];
//Required JSON Body structure which needs to be merged with Post Data
string json2 = $"{{\"time\": \"{isoTime}\",\"source\": {{\"id\": \"{name}\"
}},\"type\": \"c8y_Golf_Controller\",\"text\": \"PilotCC Data New Msg\"}}";
JObject json3 = JObject.Parse(json2);
var result = new JObject();
result.Merge(item);
result.Merge(json3);
string json4 = JsonConvert.SerializeObject(result);
client.DefaultRequestHeaders.Add("Accept",
"application/vnd.com.nsn.cumulocity.event+json"); //More Headers
var stringContent = new StringContent(json4, Encoding.UTF8,
"application/json");
stringContent.Headers.ContentType.CharSet = "";
//Making Post request
HttpResponseMessage response = await client.PostAsync("https://myurl.com",
stringContent);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
}
public class Root
{
public List<Value> Values {get; set;}
}
public class Value
{
public string RawValue { get; set; }
}
public class Station
{
[JsonProperty("ControllerName")]
public string ControllerName { get; set; }
public override string ToString()
{
return String.Format(ControllerName);
}
}
}
How do I make it better by not creating unnecessary instances of HttpClient each time foreach loop iteration in triggered and instead reuse the single instance of HttpClient for making all the http requests??
In your case, it would be enough to ...
public class Program
{
static async Task Main()
{
// Create one single instance outside the loop ...
var client = new HttpClient();
// more code here
foreach( var item in array )
{
// ... then use it.
var response = await client.GetAsync(/* yadda yadda */);
}
}
}
I have a WPF application where I need to retrieve configuration data from a remote API. The API has been tested and is working correctly returning what I believe to be the correct format. I have created a data type for the response etc etc but when I get to the line getting the response via the HttpClient it doesn't send any request to the API.
DataType :-
public class Mylist
{
public string ItemName { get; set; }
public string ItemText { get; set; }
public string ConfigName { get; set; }
public string ConfigValue { get; set; }
public string ConfigType { get; set; }
}
Code :-
string licKey = ConfigManager.GetSetting("Lic");
string Uri = ConfigManager.GetSetting("API");
string UserAPI = ConfigManager.GetSetting("Config");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Uri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(UserAPI + "?Licence=" + licKey);
var data = await response.Content.ReadAsAsync<IEnumerable<Mylist>>();
int count = 0;
List<Mylist> nudges = new List<Mylist>((IEnumerable<Nudgelist>)data);
// Do something with the data
the code builds the correct URL (https://example.com/api/Uri?Licence=licencevalue) for the request and if input manually into the browser it gives a response as per the below :-
<Mylist>
<ConfigName>cName</ConfigName>
<ConfigType>cType</ConfigType>
<ConfigValue>cValue</ConfigValue>
<ItemName>iName</NudgeName>
<ItemText>iText</NudgeText>
</Mylist>
<Mylist>
...
</Mylist>
When I run the code above and step through it then we get to the line "var response = await client.GetAsync(UserAPI + "?Licence=" + licKey);" and it just skips the rest of the code and moves onto the next call, no error raised or failures anywhere to be found.
I have run logs on the API and we are not seeing the request coming in, if we use an identical model of code for calling another API controller to call Uri2 (https://example.com/api/Uri2?Licence=licencevalue) it works fine.
Try this
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<IEnumerable<MyList>>(stringData);
}
else
{
var statusCode= response.StatusCode);
}
I am trying to serialize an object into Json and then send it to Slack. I have done this successfully without serializing but instead using "Dictionary" and "FormUrlEncodedContent" and then send it.
But now, for the purpose of making things easier and more agile, I just wanted to create one JSon-class which I could serialize and then use for every request I want to send.
Here is my code:
My JsonObject:
public class JsonObject
{
private string _token = "xoxp-MyToken";
[JsonProperty("token")]
public string token { get { return _token; } }
[JsonProperty("channel")]
public string channel { get; set; }
[JsonProperty("as_user")]
public bool as_user = true;
[JsonProperty("username")]
public string username { get;set; }
[JsonProperty("text")]
public string text { get; set; }
}
My client:
public class BpsHttpClient
{
private readonly HttpClient _httpClient = new HttpClient { };
public Uri UriMethod { get; set; }
public BpsHttpClient(string webhookUrl)
{
UriMethod = new Uri(webhookUrl);
}
public async Task<HttpResponseMessage> UploadFileAsync(StringContent requestContent)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UriMethod);
request.Content = requestContent;
var response = await _httpClient.SendAsync(request);
return response;
}
}
Main:
class MainArea
{
public static void Main( string[] args)
{
try
{
Task.WaitAll(SendMessage());
}
catch(Exception ass)
{
Console.WriteLine(ass);
Console.ReadKey();
}
}
private static async Task SendMessage()
{
var client = new BpsHttpClient("https://slack.com/api/chat.postMessage");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
JO.text = "This is so much fun :D !";
var Json = JsonConvert.SerializeObject(JO, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var StringJson = new StringContent(Json, Encoding.UTF8, "application/json");
var DeSon = JsonConvert.DeserializeObject(Json);
Console.WriteLine(DeSon); //this is for me to see if my JsonObject looks correct - it does ;)
Console.ReadKey();
var Response = await client.UploadFileAsync(StringJson);
string AnswerContent = await Response.Content.ReadAsStringAsync();
Console.WriteLine(AnswerContent);
Console.ReadKey();
}
}
When I run the code I allways get the answer:
Output:
{"ok":false,"error":"not_authed"}
although I think my JsonObject looks right - it has the token in there...
Anybody have an idea why?
So, i figured it out - I SHALL NOT put my token in the JsonObject I want to send.
The solution in this case (using httpclient) is that one has to add a header for authorization to the client, like so:
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "lé token");
and then it works.
I have a REST based API developed in JAVA. Now I am trying to call that API from a console based C# application i.e. from it's main function. I want to know is it possible to do that.
I have tried something but its not working
//I have written the below code in my class file. But the I can't find the RestClient class. What do I need to include this
static void Main(string[] args)
{
{
string endPoint = #"http:\\myRestService.com\api\";
var client = new RestClient(endPoint);
var json = client.MakeRequest();
}
}
From the documentation on asp.net site. this shows how it is done in C# , RestClient you tried to use is a lib, that encapsulate something like this sample. RestClient can be added as a nugget package.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ProductStoreClient
{
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
Uri gizmoUrl = response.Headers.Location;
// HTTP PUT
gizmo.Price = 80; // Update price
response = await client.PutAsJsonAsync(gizmoUrl, gizmo);
// HTTP DELETE
response = await client.DeleteAsync(gizmoUrl);
}
}
}
}
}