C# HttpWebRequest-远程服务器返回错误:(400) Bad Request

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14262072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:14:00  来源:igfitidea点击:

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

c#.netuploadhttpwebrequest

提问by user1301587

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 `

我收到远程服务器返回错误:(400) 运行以下代码时出现错误请求错误。我正在尝试在 http 服务器上上传 xml 文件。我的 xml 文件包含用户名、密码和域的标签,当我尝试手动连接时,我可以连接它,但是当我尝试通过此代码连接时使用相同的凭据,我收到 400 Bad Request 错误. 请建议我如何克服这个问题。谢谢`

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

采纳答案by Ben

Are you sure you should be using POST not PUT?

您确定应该使用 POST 而不是 PUT 吗?

POST is usually used with application/x-www-urlencodedformats. 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..

POST 通常与application/x-www-urlencoded格式一起使用。如果您使用的是 REST API,您可能应该使用 PUT?如果您要上传文件,您可能需要使用multipart/form-data. 并非总是如此,但通常,这是正确的做法。

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.

此外,您似乎没有使用凭据登录 - 您需要使用 HttpWebRequest 对象的 Credentials 属性来发送用户名和密码。

回答by YvesR

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.

您使用什么类型的身份验证?使用 Ben 之前所说的属性发送凭据并设置 cookie 处理程序。您已经允许重定向,如果发生任何重定向,请检查您的网络服务器(NTLM 身份验证确实如此)。如果有重定向,您需要存储主要存储在会话 cookie 中的会话。

回答by tamil

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

由于不正确的身份验证条目,将抛出 400 Bad request 错误。

  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.
  1. 检查您的 API URL 是否正确。不要附加或前置空格。
  2. 验证您的用户名和密码是否有效。输入时请检查任何拼写错误。

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

注意:主要是由于拼写更改导致的不正确的身份验证条目会出现 400 Bad request。