Pet*_*sen 0 webclient windows-phone-7 webclient-download
如果我在Consoleapp中执行此代码,它可以正常工作:
string uriString = "http://url.com/api/v1.0/d/" + Username + "/some?amount=3&offset=0";
WebClient wc = new WebClient();
wc.Headers["Content-Type"] = "application/json";
wc.Headers["Authorization"] = AuthString.Replace("\\", "");
string responseArrayKvitteringer = wc.DownloadString(uriString);
Console.WriteLine(responseArrayKvitteringer);
Run Code Online (Sandbox Code Playgroud)
但是,如果我将代码移动到我的WP7项目,如下所示:
string uriString = "http://url.com/api/v1.0/d/" + Username + "/some?amount=3&offset=0";
WebClient wc = new WebClient();
wc.Headers["Content-Type"] = "application/json";
wc.Headers["Authorization"] = AuthString.Replace("\\", "");
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(uriString));
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
Run Code Online (Sandbox Code Playgroud)
我得到了例外:使用此方法的请求不能有请求正文.
为什么?
解决方案是删除Content-type:
string uriString = "http://url.com/api/v1.0/d/" + Username + "/some?amount=3&offset=0";
WebClient wc = new WebClient();
//wc.Headers["Content-Type"] = "application/json";
wc.Headers["Authorization"] = AuthString.Replace("\\", "");
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(uriString));
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
Run Code Online (Sandbox Code Playgroud)
不确定为什么Console没有抛出,但你实际上使用的是错误的标题.
请求中的Content-Type表示POST/PUT数据的内容(HTTP请求的主体).你想要的是Accept标头.
wc.Headers["Accept"] = "application/json";
Run Code Online (Sandbox Code Playgroud)
http://msdn.microsoft.com/en-us/library/aa287673(v=VS.71).aspx