这个别人给的网址
http://139.224.32.119:8612/appapi.php/Member/cardGetInfo.html?card=863100001100308137
这是用浏览器打开得到的内容:
{"result":1,"info":{"id":"5746","name":"\u6850\u5e90\u4f53\u9a8c\u536120","nickname":"","creattime":"2016-06-23 16:43:53","password":"123456","pic":"","sex":"\u7537","email":"","phone":"","signature":""}}
请问用C#代码怎么调用这个网址的接口,并且解析的sex:男的?求大神指教
var json; using (WebClient wc = new WebClient()) { json = wc.DownloadString("url"); } JObject model = JObject.Parse(json); var sex = model["info"]["sex"];
JObject是Newtonsoft.Json的,你也可以使用其它library
你的方法,挺不错的,解析出来是对的,问一下,你能用js告诉我代码怎么写吗?
@IT_zl:
var sex; $.ajax({ url: 'http://139.224.32.119:8612/appapi.php/Member/cardGetInfo.html?card=863100001100308137', }).done(function(data) { sex = data.info.sex; })
js不就更簡單,是這問這個?
httpclient getasync
你说的我不会实现,我是个菜鸟
@IT_zl: 是个菜鸟,还自豪了呀。
给了你关键字 就是msdn多搜搜,别人给的代码,永远是别人的。
要鱼还是要渔
var type = "utf-8"; var Url = "http://139.224.32.119:8612/appapi.php/Member/cardGetInfo.html?card=863100001100308137" System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) string data = ""; using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { data = reader.ReadToEnd(); }
你这个方法得到的只是浏览器打开的结果,没法转换
就是利用http请求,然后将获取的json字符串解析成对象,就可以取到你想要的数据了。
一看就知道你是大神,可是我是菜鸟,基本什么都不懂
@IT_zl: 大神不敢当,只是提供给你一个思路,其他的你可以自己查下资料,这样更深刻。
你说的方法我懂得,可是具体实现我不会
@IT_zl: 好吧,那你可以先参考给你代码的回答了。
...
?
static void Main(string[] args) { var type = "utf-8"; var Url = "http://139.224.32.119:8612/appapi.php/Member/cardGetInfo.html?card=863100001100308137"; System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); string data = ""; using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { data = reader.ReadToEnd(); } data = Regex.Unescape(data); Console.WriteLine(data); Console.ReadKey(); }
你的方法也是正确的,谢谢,我测试了
using (HttpClient client = new HttpClient()) { HttpResponseMessage response = Task.Run( async () => await client.GetAsync( "http://139.224.32.119:8612/appapi.php/Member/cardGetInfo.html?card=863100001100308137")) .Result; var restulStr = Task.Run(async () => await response.Content.ReadAsStringAsync()).Result; var resultJson = JsonConvert.DeserializeObject<JObject>(restulStr); var sex = resultJson.SelectToken("info.sex").Value<string>(); }
这个方法,可能有个类你没告诉我,复制出来用,有几个时报错的,但是也要谢谢你的解答
nuget下载newtonsoft.net引用,然后参考上边几人说的
嗯,是的,我就这么做的,还在测试结果了