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

4

14

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();
    }
}
Velamen answered 10/1, 2013 at 16:4 Comment(2)
I doubt it'd make any difference but you could try removing the trailing space from the URL and using "POST" block-caps (or there must be a constant for this?). Can you see anything in the server logs? You could also try catching the two requests, manually and through the app, in Fiddler to look for differences. Does your ASPX definitely accept POSTs of XML text, though?Naive
No it is not making any differences !!Velamen
S
13
  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.

Spannew answered 10/1, 2013 at 16:46 Comment(2)
POST in rest api are used to create, PUT to update data. So both are ok depending what he wants to do.Cocks
The second part of this is far more likely to be an issue (for the reason YvesR commented 11 years ago): a credential or header issue.Ehrlich
A
4

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.

Aurlie answered 14/10, 2015 at 9:33 Comment(1)
For me, it was the API URL. I forgot to put the id of the model I wanted to update with my PUT request. Thanks!Abwatt
C
0

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.

Cocks answered 10/1, 2013 at 16:57 Comment(1)
This is more of a comment than an answer.Ehrlich
G
-1

//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();
}
Glyconeogenesis answered 20/1, 2022 at 11:59 Comment(1)
It is unlikely that the OP's problem is the text encoding, the majority of web apps do support UTF-8Lotion

© 2022 - 2024 — McMap. All rights reserved.