剛接觸metro不久,就接到開發微博接口的任務,搞了好久。下面分享下開發過程
注意:1、metro下沒有webbrowser控件,網上很多的實現都是基於webbrowser開發的。
2、metro有WebView控件,很多基於網頁認證的接口就要用到此控件。QQ的接口是基於網頁的。
先要判斷網絡連接,可以參考下這個Windows.Networking.Connectivity命名空間。
第一種post方法:
HttpClient client = new HttpClient(); //准備POST的數據 var postData = new List<KeyValuePair<string, string>>(); postData.Add(new KeyValuePair<string, string>("access_token", "你的access_token")); postData.Add(new KeyValuePair<string, string>("oauth_consumer_key", "你的App_Id")); postData.Add(new KeyValuePair<string, string>("openid", "你的Openid")); HttpContent httpcontent = new FormUrlEncodedContent(postData); HttpResponseMessage response = await client.PostAsync("接口地址", httpcontent); //返回的信息 string responseBody = await response.Content.ReadAsStringAsync();
第二種post方法:
HttpClient client = new HttpClient(); //准備POST的數據 MultipartFormDataContent httpcontent = new MultipartFormDataContent(); HttpContent accessContent = new StringContent(access_token); accessContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); httpcontent.Add(accessContent, "access_token"); //傳輸二進制圖片 Stream stream = new MemoryStream(pic); HttpContent piccontent = new StreamContent(stream); piccontent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/form-data"); httpcontent.Add(statusContent, "status"); //發起POST連接 HttpResponseMessage response = await client.PostAsync("接口地址", httpcontent); //返回的信息 responseBody = await response.Content.ReadAsStringAsync();
第三種post(比較大眾的做法):
先把內容放到一個stream中
HttpContent PostContent = new StreamContent(stream); PostContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/form-data; boundary=" + boundary); HttpClient client = new HttpClient(); HttpResponseMessage response = await client.PostAsync("接口地址", PostContent);
記得要把指針指向stream的開始,不然發過去的是stream的結尾,一片空白。
具體可以參考微軟給的這個例子:http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664