get Json Data From URL in C# - json

I am new to json i want get json data from a link, here from web search i have written code
private void button1_Click(object sender, EventArgs e)
{
string url = #"http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers";
using (WebClient wc=new WebClient())
{
json = wc.DownloadString(url);
}
string path = #"ouptputfileJSON.json";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(json);
}
}
}
When i execute this code i'm getting output in html page. how to get in json data of select product in the link provided

Here is the rest endpoint you are looking for:
http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-
inTRONICS_Business-Site/-;loc=en_US;cur=USD/products/1599925
Documentation about other rest endpoints:
https://support.intershop.com/kb/index.php/Display/T27711

Because
http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers
Is webpage and not API endpoint so you need to find proper endpoint from where you want to get data
Once you get Proper Endpoint you can use below
Here is an example how you can use httpclient to make a request
static void Main()
{
Task t = new Task(DownloadPageAsync);
t.Start();
Console.WriteLine("Downloading page...");
Console.ReadLine();
}
static async void DownloadPageAsync()
{
// ... Endpoint
string page = "request URL";
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
Console.WriteLine(result);
}
}

Related

JSON.NET: getting json from external source with streams, how to get just one value?

I have the following code:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
using (Stream stream = client.GetStreamAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result)
using (StreamReader streamReader = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
//What do I do here to get my one value?
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
I got this from the documentation over at the JSON.NET website. The reason being that I don't want to load the whole string, but piece by piece. The response is as follows:
[{"brandstof_omschrijving":"Benzine","brandstof_volgnummer":"1","brandstofverbruik_buiten":"6.60","brandstofverbruik_gecombineerd":"8.20","brandstofverbruik_stad":"11.10","co2_uitstoot_gecombineerd":"196","emissiecode_omschrijving":"Euro 4","geluidsniveau_rijdend":"71","geluidsniveau_stationair":"82","kenteken":"61SFSL","milieuklasse_eg_goedkeuring_licht":"70/220*2001/100B","nettomaximumvermogen":"99.00","toerental_geluidsniveau":"4125"}]
I.e., it returns an array with one json object, and I want to retrieve just one value in there, using a stream. How might I do this?
You could try the following
using System;
using System.Net.Http;
using Newtonsoft;
public class Program {
public static void Main() {
var client = new HttpClient();
var json = client.GetStringAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result;
var data = JsonConvert.DeserializeObject<dynamic>(json);
string value = data[0].co2_uitstoot_gecombineerd;
Console.WriteLine(value);
Console.WriteLine("Press any key to continue...");
Console.Read();
}
}

Calling a webservice repeatedly and export data

I have a webservice which accepts a parameter and gives back result in a JSON message format.
http://portLocation/Company/WebService.asmx/Operation?parameter1=XX
My objective is to repeatedly call this webservice with the parameters in a CSV File.
What would be the ideal way to do it.
Here is a simple working concept for C#.
You'll need to adjust it for your needs.
static void Main(string[] args)
{
string datafile = "data.csv";
StringBuilder sbUrl = new StringBuilder("http://portLocation/Company/WebService.asmx/Operation");
List<string> fileContents = System.IO.File.ReadAllLines(datafile).ToList();
using (HttpClient httpClient = new HttpClient())
{
foreach (string item in fileContents)
{
string[] data = item.Split(',');
sbUrl.AppendFormat("?parameter1={0}", data[0]);
sbUrl.AppendFormat("&parameter2={0}", data[1]);
sbUrl.AppendFormat("&parameter3={0}", data[2]);
sbUrl.AppendFormat("&parameter4={0}", data[3]);
var response = httpClient.GetAsync(sbUrl.ToString());
}
}
}

Detecting when a web service post has occured

I just wrote a simple windows 8 form that post to web service api. It works fine. But my challenge is been able to determine when the post operation was a success and a failure. I dont know how to return a value cos aysnc Task is not allowing a return type.
//This class does the post to web service
public class B2cMobileuserService : IB2cMobileuserService
{
private string RegisterUserUrl = RestfulUrl.RegisterMobileUser;
private readonly HttpClient _client = new HttpClient();
public async Task RegisterMobileUser(B2cMobileuserView user)
{
var jsonString = Serialize(user);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var result = await _client.PostAsync(RegisterUserUrl, content);
}
}
//This class calls the one above
public class WebserviceProcessor
{
//declaring all the service objects that would be used
IB2cMobileuserService mobileuserService = null;
public WebserviceProcessor() {
mobileuserService = new B2cMobileuserService();
}
//This method is going to post values to the web serever
public async void RegisterUser(B2cMobileuserView mobileuser) {
mobileuserService.RegisterMobileUser(mobileuser);
}
}
//Then the code below is from my .xaml user interface that calls the class that sends to webservice
private void Button_Click(object sender, RoutedEventArgs e)
{
B2cMobileuserView user = new B2cMobileuserView();
user.Name = name.Text;
user.Email = email.Text;
user.PhoneType = "Windows Mobile";
user.BrowserType = "None";
user.CountryName = "Nigeria";
user.UserPhoneID = phone.Text;
Serviceprocessor.RegisterUser(user);
progressBar.Visibility = Visibility.Visible;
}
Please I dont know how to return a value cos when I try I get the error that says async method must be void.
I need to set a way to know when the post was a success based on the return value from the web service.
To ensure the POST was successful, call HttpResponseMessage.EnsureSuccessStatusCode:
public async Task RegisterMobileUser(B2cMobileuserView user)
{
var jsonString = Serialize(user);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var result = await _client.PostAsync(RegisterUserUrl, content);
result.EnsureSuccessStatusCode();
}
If you want to return a value, use a Task<T> return type instead of Task.
On a side note, avoid async void; use async Task instead of async void unless the compiler forces you to write async void:
//This method is going to post values to the web serever
public Task RegisterUser(B2cMobileuserView mobileuser) {
return mobileuserService.RegisterMobileUser(mobileuser);
}
Also, you should name your asynchronous methods ending in *Async:
//This method is going to post values to the web serever
public Task RegisterUserAsync(B2cMobileuserView mobileuser) {
return mobileuserService.RegisterMobileUserAsync(mobileuser);
}
You may find my async intro and MSDN article on async best practices helpful.

how to handle http 400 and 401 error while using webclient to download JSON

I am using an api that returns an error 400 if URL is invalid and error 401 if daily qouta is exhausted by 50%. it also returns the json but am not able to download this json as an exception occurs if these error occurs. the api am using is
http://www.sharedcount.com/documentation.php
the code am using write now is...
private void _download_serialized_json_data(Uri Url)
{
var webClient = new WebClient();
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(Url);
}
catch (Exception) { }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
try
{
Json = e.Result;
}
catch (Exception ex)
{
}
if(Json!=null)
{
data=JsonConvert.DeserializeObject<RootObject>(Json);
result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne;
}
else
{
result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%.";
}
}
currently am showing both errors if exception occurs. but i want to download the json and display that. how should i do that
To get the response content, you will need to use System.Net.Http.HttpClient instead. Install it from here: Microsoft HTTP Client Libraries
Then try this:
private async void Foo2()
{
Uri uri = new Uri("http://localhost/fooooo");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
HttpStatusCode statusCode = response.StatusCode; // E.g.: 404
string reason = response.ReasonPhrase; // E.g.: Not Found
string jsonString = await response.Content.ReadAsStringAsync(); // The response content.
}
You can try something like this,
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
if(e.Error != null)
{
//Some error occured, show the error message
var ErrorMsg = e.Error.Message;
}
else
{
//Got some response .. rest of your code
Json = e.Result;
}
}
I ran into this same issue using WebClient, I saw the error response stream being captured in Fiddler, but my .NET code was catching the exception and did not appear to be capturing the response stream.
You can read the Response stream from the WebException object to get the response data stream out.
using (System.Net.WebClient client = new System.Net.WebClient())
{
string response = "";
try
{
response = client.UploadString(someURL, "user=billy&pass=12345");
}
catch(WebException ex)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
string exResponse = sr.ReadToEnd();
Console.WriteLine(exResponse);
}
}
}

How do I read the basic authorization in a ASP.Net MVC4 api GET request

I have a phone app that trys to GET data from my web api using RestSharp
private void ButtonTestTap(object sender, EventArgs e)
{
var client = new RestClient
{
CookieContainer = new CookieContainer(),
BaseUrl = "http://localhost:21688/api/game",
Authenticator = new HttpBasicAuthenticator("muhcow", "123456")
};
RestRequest request = new RestRequest(Method.GET);
request.AddParameter("id", 5);
//request.AddBody(5);
client.GetAsync<LoginResult>(request, (response, ds) =>
{
System.Diagnostics.Debug.WriteLine(response.StatusDescription);
System.Diagnostics.Debug.WriteLine(response.Data);
System.Diagnostics.Debug.WriteLine(response.Content);
});
}
And then want to read the Authenticator = new HttpBasicAuthenticator("muhcow", "123456") when my api server recieves this GET request so I can verify the user, but I am not sure how to read the data.
I have this
public class GameController : ApiController
{
// GET /api/game/5
public string Get(int id)
{
var sdf2 = ControllerContext.Request.Headers.Authorization.Parameter;
//return LoginManager.VerifyLogin(loginData);
return "Some data";
}
But sdf2 just has a wierd value "bXVoY293OjEyMzQ1Ng=="
That header is base64-encoded. Apply Convert.FromBase64String() to it and you'll see the contents.
Authorization.Parameter is base64 encoded. You can look at an example of how to decode it here http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/
System.Text.Encoding.UTF8.GetString (Convert.FromBase64String (this.ControllerContext
.Request .Headers.Authorization.Parameter ))
the result is
"muhcow", "123456"