简体   繁体   中英

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

I am getting The remote server returned an error: (400) Bad Request error while running the following code. I am trying to upload xml file on the http server. My xml file contains tag for the username,password and domain and when i am trying to connect is manually i am able to connect it,but using same credentials when i am trying to connect it through this code, i am getting 400 Bad Request error. Please suggest me how to overcome this issue. Thanks `

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

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..

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.

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

\/\/use "ASCII" or try with another encoding scheme instead of "UTF8".

using (StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.UTF8))
{
    postStream.Write(postData);
    postStream.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM