【发布时间】:2012-03-22 14:39:33
【问题描述】:
如果我在 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);
但如果我像这样将代码移动到我的 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);
}
我遇到了异常:使用此方法的请求不能有请求正文。
为什么?
解决办法是去掉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);
}
【问题讨论】:
-
出于各种原因以及更多(!),我建议您尝试使用 WebRequest 而不是 WebClient 包装器...... WebClient 确实有一些“技巧”我会导致这个问题,而 WebRequest 可以让您更好地控制 Http 通信!
-
嗨佩德罗。我已经试过了。它给了我同样的结果。