http://cathval.com/csharp/4159
I found out how to handle JSON data by referring to this site, but how can I receive JSON information from WebAPI like the URL below in String?
http://weather.livedoor.com/forecast/webservice/json/v1?city=400040
c# json http
HttpWebRequest
class may be used, but
It is easy to use the WebClient.DownloadString method in the WebClient class.
Examples of use:
using System;
using System.IO;
using System.Net;
namespace HTTPGET
{
class HttpGet
{
static void Main (string[]args)
{
using(WebClient=newWebClient())
{
string str = webClient.DownloadString("http://weather.livedoor.com/forecast/webservice/json/v1?city=400040");
Console.Write(str);
}
}
}
}
If you wanted to create a RESTful service, the ASP.NET Web API was designed with this goal in mind.
For example, HttpClient class makes it easy to receive async.
using System;
using System.Threading.Tasks;
You can install `System.Net.Http` or `Microsoft.AspNet.WebApi.Client` in using System.Net.Http;//nuget.
namespace httpclient_test
{
class program
{
static void Main (string[]args)
{
stringuri="http://weather.livedoor.com/forecast/webservice/json/v1?city=400040";
GetString(uri).Wait();
}
public static async Task GetString (stringuri)
{
using(var httpClient=new HttpClient())
{
string response = wait httpClient.GetStringAsync(uri);
Console.Write(response);
}
}
}
}
When sending HTTP requests over .NET, the basic is WebRequest
, and WebClient
and HttpClient
also use WebRequest
internally.
using System;
using System.IO;
using System.Net;
using System.Text;
static class program
{
static void Main (string[]args)
{
var req = WebRequest.Create("http://weather.livedoor.com/forecast/webservice/json/v1?city=400040");
using(var res=req.GetResponse())
using(varsr=new StreamReader(res.GetResponseStream(), Encoding.ASCII))
{
Console.WriteLine(sr.ReadToEnd());
}
Console.ReadKey();
}
}
Also, if you only want the analysis results, you should use Stream
instead of String
.
dynamic json;
using(var res=req.GetResponse())
using(vars=res.GetResponseStream())
{
json=DynamicJson.Parse(s);
}
© 2024 OneMinuteCode. All rights reserved.