HttpWebRequest - the remote server responded with an error: (400) Bad Request

I get The remote server returned an error: (400) Error An error occurred while running the following code. I am trying to upload an XML file on an http server. My XML file contains a tag for username, password and domain, and when I try to connect, I can manually connect to it, but using the same credentials, when I try to connect through this code, I get a 400 Bad Request error, Please , suggest me how to overcome this problem. 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(); } }` 
+7
source share
3 answers

Are you sure you should use POST not PUT?

POST is commonly used with application/x-www-urlencoded formats. If you use the REST API, maybe you are using PUT? If you are uploading a file, you probably need to use multipart/form-data . Not always, but usually this is what needs to be done.

In addition, you do not use login credentials — you need to use the Credentials property of the HttpWebRequest object to send the username and password.

+11
source

400 Bad request. An error will result in an incorrect entry due to authentication errors.

  • Check the API URL correctly or incorrectly. Do not leave any spaces in front or finally.
  • Verify your username and password. Please check for any spell error during input.

Note. Mostly due to invalid authentication entries due to spell changes, a 400 Bad request will occur.

+2
source

What type of authentication do you use? Send the credentials using the properties Ben said earlier and set up a cookie handler. You already allow redirection, check your web server if redirection occurs (NTLM auth does this for sure). If there is a redirect, you need to save the session, which is mainly stored in the session cookie.

0
source

All Articles