最近好多应用都用到了HTTP,然后每次使用,都重新找一遍资料,没有把知识总结起来,学不到什么。现在总结下之前遇到的情况的处理方式。
1:WP8.1 httpRequest异步读取数据 GET
1 public async void ReadUrlAsync(int tempid) 2 { 3 4 5 using (var client = new HttpClient()) 6 { 7 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");//header什么的添加,修改 8 var data = await client.GetStringAsync("http://baidu.com"); 9 10 json(data.ToString());//对得到的数据的处理 11 } 13 }
2:httpRequest 同步 GET
public static string GetData() { string URL = "http://baidu.com"; HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(URL); webReq.Method = "get"; try { HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if (retString != "") return ToUnicode(retString); else return "-1"; } catch { return "-1"; } }
3:同步 Post
public void PostData(string strText) { string URL = "baidu.com"; string strPostdata = "A=213&B=213"; //要post的数据 Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "post";byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); reader.readtoend(); }
4:异步Post wp
var values = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("api_key", "12345"), new KeyValuePair<string, string>("game_id", "123456") }; var httpClient = new HttpClient(new HttpClientHandler()); HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(values)); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync();
原来的例子都是网上找的,出处记不清了,最后一个例子是在http://stackoverflow.com/questions/16138275/simple-http-post-in-windows-phone-8
接触不久,可能有好多不恰当的地方,如果您发现了,请务必指正,十分感谢。