1

I'm just trying to get a REST-API response from a POST request.

Getting this error:

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse

Here is my code:

public enum httpVerb
{
    GET,
    POST,
    PUT,
    DELETE
}

class RestProvider
{
    public string uri { get; set; }
    public httpVerb httpMethod { get; set; }

    public RestProvider()
    {
        uri = "";
        httpMethod = httpVerb.POST;
    }

    public string makeRequest()
    {
        string strResponseValue = string.Empty;        
        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = httpMethod.ToString();
        request.ContentLength = uri.Length;
        request.ContentType = "application/x-www-form-urlencoded";
        HttpWebResponse response = null;

        try
        {
            response = (HttpWebResponse)request.GetResponse();

            using (Stream responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        strResponseValue = reader.ReadToEnd();
                    }
                }
            }
        }

        catch (Exception ex)
        {
            strResponseValue = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
        }

        finally
        {
            if (response != null)
            {
                ((IDisposable)response).Dispose();
            }
        }

        return strResponseValue;
    }
}

Any ideas?

k.troy2012
  • 344
  • 4
  • 21

1 Answers1

1

This: request.ContentLength = uri.Length; is wrong. That's not what ContentLength is for. Either leave ContentLength alone, (in which case it will be zero,) or send some request content and set ContentLength to the length of the request content that you are sending. The uri is not a request content.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • How do i get the length of the whole request? – k.troy2012 Aug 01 '17 at 15:18
  • `ContentLength` is not the length of the whole request. It is the length of the ***request content***. And you don't seem to be sending any ***request content***. So leave `ContentLength` to zero. If you were sending a ***request content***, then you would need to set `ContentLength` to be the length, in bytes, of the ***request content***. – Mike Nakis Aug 01 '17 at 15:58