刚接触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