Pergunta

If I execute this code in a Consoleapp it works fine:

        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);

But if I move the code to my WP7 project like this:

        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);
    }

I got the exception: A request with this method cannot have a request body.

Why?

The solution is to remove the 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);
    }
Foi útil?

Solução

Not sure why Console is not throwing, but you are essentially using the wrong header.

Content-Type on a request denotes the content of the POST/PUT data (the body of the HTTP request). What you want is the Accept header.

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

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top