第一种
public class UserInfo
{
public int id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string sex { get; set; }
public int age { get; set; }
}
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:36793");
// Add an Accept header for JSON format.
// 为JSON格式添加一个Accept报头
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/UserInfo").Result;
if (response.IsSuccessStatusCode)
{
var products = response.Content.ReadAsAsync<IEnumerable<UserInfo>>().Result;
foreach (var x in products)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4};", x.id, x.username, x.password, x.sex, x.age);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
Console.ReadLine();
第二种
UserInfo userinfo = new UserInfo();
string url = string.Format("http://localhost:36793/api/UserInfo");
var by = new System.Net.WebClient().DownloadData(url);
var result = System.Text.Encoding.UTF8.GetString(by);
Console.WriteLine(result);//直接将获取的数据以字符串形式显示。
var userinfolist = JsonConvert.DeserializeObject<IList<UserInfo>>(result);
userinfolist.ToList().ForEach(x => Console.WriteLine(x.id + "---" + x.username + "---" + x.password + "---" + x.sex + "---" + x.age));
foreach (var outx in userinfolist)
{
Console.WriteLine(outx.id + "---" + outx.username + "---" + outx.password + "---" + outx.sex + "---" + outx.age);
}
//将获取到的字符串转换为json格式并输出。
Console.ReadLine();
命名空间
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using Newtonsoft.Json;
using System.Web.Http;