Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,

I am trying to call a web service by passing JSON data. The web service accepts the authentication, where we need to pass the username and password to authenticate.
I am sorry guys, I couldn't disclose the URL and the Username.

Below is my method to do the job.
C#
private static void MakeRequest(string url, string user_name)
       {
           try
           {
               var webAddr = url;
               var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
               httpWebRequest.ContentType = "application/json;";
               httpWebRequest.Method = "POST";
               //password is blank
               var credentialBuffer = new UTF8Encoding().GetBytes(user_name + ":" + "");
               httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);

               using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
               {
                   string json = "{\"x\":\"true\"}";

                   streamWriter.Write(json);
                   streamWriter.Flush();
               }

               var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
               using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
               {
                   var result = streamReader.ReadToEnd();
               }
           }
           catch (Exception ex)
           {

               throw;
           }
}


When I call the method by passing URL and the username, it is returning error as "The remote server returned an error: (422) Unprocessable Entity."
I guess I am not using the proper authentication method.

Please help.
Posted
Updated 31-Dec-14 20:29pm
v3
Comments
Kornfeld Eliyahu Peter 1-Jan-15 2:32am    
We can not know about the 'proper' authentication method of your web service! How can we help?!
Praveen Kumar Upadhyay 1-Jan-15 2:35am    
My question is, am I doing the write code to authenticate the username and password??
Kornfeld Eliyahu Peter 1-Jan-15 2:38am    
There are different way to authenticate your call and all of them can be 'right'...We can not know - from the info you gave - what the way your web service expect...
Praveen Kumar Upadhyay 1-Jan-15 2:41am    
So how do I do this, should I ask my web service to cross check my code?
Kornfeld Eliyahu Peter 1-Jan-15 2:42am    
If you din't created the web service, you should talk to who did...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900