WP7上的WebClient - 投掷"使用此方法的请求不能有请求正文"

时间:2012-03-22 14:39:34

标签: windows-phone-7 webclient 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);

但是,如果我将代码移动到我的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);
    }

1 个答案:

答案 0 :(得分:6)

不确定为什么Console没有投掷,但你实际上使用了错误的标题。

请求中的Content-Type表示POST / PUT数据的内容(HTTP请求的主体)。你想要的是Accept标题。

wc.Headers["Accept"] = "application/json";

http://msdn.microsoft.com/en-us/library/aa287673(v=VS.71).aspx