Search code examples
c#.netuploadhttpwebrequest

HttpWebRequest - The remote server returned an error: (400) Bad Request


I am trying to upload an XML file to the HTTP server. My XML file contains a tag for the username, password and domain, and I am able to connect to it when I try to connect manually, but using the same credentials when I am trying to connect it through this code, I am getting:

The remote server returned an error: (400) Bad Request error

public static void UploadHttp(string xml)     
{

    string txtResults = string.Empty;
    try
    {
        string url = "http://my.server.com/upload.aspx ";
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.KeepAlive = false;
        request.SendChunked = true;
        request.AllowAutoRedirect = true;
        request.Method = "Post";
        request.ContentType = "text/xml";
        var encoder = new UTF8Encoding();
        var data = encoder.GetBytes(xml);
        request.ContentLength = data.Length;
        var reqStream = request.GetRequestStream();
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();
        WebResponse response = null;
        response = request.GetResponse();
        var reader = new StreamReader(response.GetResponseStream());
        var str = reader.ReadToEnd();
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            HttpWebResponse err = ex.Response as HttpWebResponse;
            if (err != null)
            {
                string htmlResponse = new StreamReader(err.GetResponseStream()).ReadToEnd();
                txtResults = string.Format("{0} {1}", err.StatusDescription, htmlResponse);
            }
        }
        else
        {

        }
    }
    catch (Exception ex)
    {
        txtResults = ex.ToString();
    }
}

Solution

    1. Are you sure you should be using POST not PUT?

      POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do.

    2. Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.