views:

41

answers:

2

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)

+1  A: 

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

Onkelborg
A: 

I needed to add:

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

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

SorinA.
I think I have an answer to your question: http://msdn.microsoft.com/en-us/library/system.net.networkcredential.aspx . Try using a CredentialCache as in the example. The problem is, as I understand, that the client doesn't know how to authenticate since, at the first request, the server hasn't told that yet. However, in the first response that's clear: it's Basic authentication. With CredentialCache you can specify what authentication scheme to use and avoid the error on your first request. It's not a bug, it's a limitation of the HTTP protocol.
Onkelborg
Hy Onkelborg, i modified my code as suggested in the article but i receive the 500 error from the server. if i just add the header like i did it works
SorinA.