HttpWebRequest POST 给出 500 服务器错误

发布于 2024-09-28 06:23:27 字数 3141 浏览 2 评论 0原文

我需要从我的应用程序中创建一个经过身份验证的 httpwebrequest。对我的请求的响应应该是 json 格式。为此,我使用下面的代码:

// Create the web request 
        Uri address = new Uri("http://www.mysite.com/remote/user/login/format/json");
        HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
        request.Method = "POST";
        request.UseDefaultCredentials = false;
        request.Credentials = new NetworkCredential(UserName, Password);
        request.PreAuthenticate = true;
        request.ContentType = "application/x-www-form-urlencoded";
        request.Accept = "application/json";

        string data = string.Format("username={0}&password={1}", otherusername, otherpassword);
        // Create a byte array of the data we want to send  
        byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

        // Set the content length in the request headers  
        request.ContentLength = byteData.Length;

         //Write data  
        using (Stream postStream = request.GetRequestStream())
        {
            postStream.Write(byteData, 0, byteData.Length);
        }


        // Get response
        try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output  
                jsonResponse = reader.ReadToEnd();
                reader.Close();
            }

            user = new User();
            JObject o = JObject.Parse(jsonResponse);
            user.Unguessable_id = (string)o["unguessable_id"];
            user.Print_id = (string)o["print_id"];
            user.Rrid = (string)o["rrid"];
            user.Raid = (string)o["raid"];

        }
        catch (WebException ex) {
            errorMessage = ex.Message;
        }

问题是第一次调用它总是在服务器上给出 500 错误。并且请求失败。如果我重做调用(通过在浏览器中刷新),请求就会成功。

在正常情况下,请求应该是这样的:

POST /remote/user/login/format/json HTTP/1.1
Host: <yourhost>

username=user&password=pass

但是当服务器发出 500 错误时,他收到了这样的信息:

username=user&password=passwordPOST /remote/user/login/format/json HTTP/1.1

知道为什么会发生这种情况吗?在我的测试应用程序中,如果我刷新发出 httpwebrequest 的页面,则调用成功。

编辑: 安装 Fiddler 后,发出的请求如下所示:

=>产生 500 的那个

POST http://www.mysite.com/remote/user/login/format/json HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Host: www.mysite.com
Content-Length: 30
Expect: 100-continue
Connection: Keep-Alive

username=user&password=pass

=>刷新时所做的

POST http://www.mysite.com/remote/user/login/format/json HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Authorization: Basic ZGNpOkFpR2g3YWVj
Host: www.mysite.com
Content-Length: 30
Expect: 100-continue
Connection: Keep-Alive

username=user&password=pass

似乎 Authorization: Basic ZGNpOkFpR2g3YWVj 未包含在第一个请求中...为什么会发生这种情况?(我对两个请求使用相同的代码)

I need to make from my app an authentificated httpwebrequest. the response to my request should be in json format. for this i'm using the code below:

// Create the web request 
        Uri address = new Uri("http://www.mysite.com/remote/user/login/format/json");
        HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
        request.Method = "POST";
        request.UseDefaultCredentials = false;
        request.Credentials = new NetworkCredential(UserName, Password);
        request.PreAuthenticate = true;
        request.ContentType = "application/x-www-form-urlencoded";
        request.Accept = "application/json";

        string data = string.Format("username={0}&password={1}", otherusername, otherpassword);
        // Create a byte array of the data we want to send  
        byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

        // Set the content length in the request headers  
        request.ContentLength = byteData.Length;

         //Write data  
        using (Stream postStream = request.GetRequestStream())
        {
            postStream.Write(byteData, 0, byteData.Length);
        }


        // Get response
        try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output  
                jsonResponse = reader.ReadToEnd();
                reader.Close();
            }

            user = new User();
            JObject o = JObject.Parse(jsonResponse);
            user.Unguessable_id = (string)o["unguessable_id"];
            user.Print_id = (string)o["print_id"];
            user.Rrid = (string)o["rrid"];
            user.Raid = (string)o["raid"];

        }
        catch (WebException ex) {
            errorMessage = ex.Message;
        }

the problem is that the very first call it always gives a 500 error on the server. and the request fails. if i redo the call(by making an refresh in my browser) the request is successful.

the request should look like this in normal conditions:

POST /remote/user/login/format/json HTTP/1.1
Host: <yourhost>

username=user&password=pass

but when the server sends out the 500 error he received something like this:

username=user&password=passwordPOST /remote/user/login/format/json HTTP/1.1

any idea why this is happening? in my test app if i refresh the page that makes the httpwebrequest the call is successful.

EDIT:
after installing Fiddler the requests made look like this:

=> the one that generates 500

POST http://www.mysite.com/remote/user/login/format/json HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Host: www.mysite.com
Content-Length: 30
Expect: 100-continue
Connection: Keep-Alive

username=user&password=pass

=> the one made on refresh

POST http://www.mysite.com/remote/user/login/format/json HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Authorization: Basic ZGNpOkFpR2g3YWVj
Host: www.mysite.com
Content-Length: 30
Expect: 100-continue
Connection: Keep-Alive

username=user&password=pass

it seems that Authorization: Basic ZGNpOkFpR2g3YWVj is not included in the first request...why is that happening?(i'm using the same code for both requests)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨夜星沙 2024-10-05 06:23:27

我建议您安装 Fiddler 看看到底发生了什么

I would advice you to install Fiddler to see what's really happening

北斗星光 2024-10-05 06:23:27

我需要添加:

request.Headers.Add("Authorization: Basic ZGNpOkFpR2g3YWVj");

奇怪的是,对于第二个请求,它是自动添加的..

I needed to add:

request.Headers.Add("Authorization: Basic ZGNpOkFpR2g3YWVj");

weird though that for the second request it was added automatically..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文