kformeck kformeck - 1 month ago 21
HTTP Question

411 - Length Required When Attempting to POST

I am developing a mobile application using Xamarin. This makes it so I cannot call webRequest.ContentLength = 0.

Here is how I am attempting to post:

Client calls:

await new AssetEndpoint().UpdateStatus(Authentication, CurrentAsset, ApprovalStatuses[0]);


AssetEndpoint.UpdateStatus:

public Task UpdateStatus(Authentication auth, Asset asset, ApprovalStatus newStatus)
{
return PostResponseAsync(auth, string.Format(
ApiUpdateStatus, asset.UID, newStatus.Id));
}


Endpoint.PostResponseAsync:

protected async Task<string> PostResponseAsync(Authentication auth, string apiCall)
{
var request = WebRequest.Create(string.Concat(BaseUriPath, apiCall)) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
request.Headers["Authorization"] = string.Concat("bearer ", auth.Token.Value);
var response = await request.GetResponseAsync().ConfigureAwait(false);
using (var reader = new StreamReader(response.GetResponseStream()))
{
return await reader.ReadToEndAsync();
}
}


So I do go about fixing this error? I cannot seem to figure out how to set the content length.

Answer
public class RestClientTest
{
    public static async Task<string> Login()
    {
        try
        {
            var request = WebRequest.CreateHttp(path);
            request.Headers["Username"] = "xxxxxxxxx";
            request.Headers["Password"] = "xxxxxxxxxxx";
            request.ContentType = "application/json";
            request.Method = "POST";
            byte[] byteArray = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35 };
            using (Stream dataStream = await request.GetRequestStreamAsync())
            {
                await dataStream.WriteAsync(byteArray, 0, byteArray.Length);
            }
            var response = await request.GetResponseAsync().ConfigureAwait(false);
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                string resp = await reader.ReadToEndAsync();
                return resp;
            }
        }
        catch (Exception ex)
        {
            return "Error";
        }
    }
}

If that doesn't work for you I can provide HttpClient sample if you want to try. Without knowing what you are posting I cannot help more. I also tested this code without sending any data in the body and it works too.