0

I am trying to call a web service by making a Http REST call. But I get a "Bad Request" status in the response. I know this means I have something going wrong with my syntax for the request, but I am unable to find it out.

Here is my code:-

public void GetToken ()
        {
            HttpWebRequest hwr =(HttpWebRequest) WebRequest.Create(string.Format("https://login.windows.net/{0}/oauth2/token", myApp.DomainName));
            hwr.Method = "POST";
            hwr.ContentType = "myApplication/x-www-form-urlencoded";
            hwr.BeginGetRequestStream(new AsyncCallback(SendTokenEndpointRequest), hwr);
        }

        protected void SendTokenEndpointRequest (IAsyncResult rez)
        {
            HttpWebRequest hwr = (HttpWebRequest)rez.AsyncState;   
            byte[] bodyBits = Encoding.UTF8.GetBytes(
                string.Format(
                    "grant_type=authorization_code&code={0}&client_id={1}&redirect_uri={2}",
                    myApp.Code, 
                    myApp.ClientId, 
                    HttpUtility.UrlEncode(myApp.RedirectUri)));
            Stream st = hwr.EndGetRequestStream(rez);
            st.Write(bodyBits, 0, bodyBits.Length);
            st.Close();
            hwr.BeginGetResponse(new AsyncCallback(RetrieveTokenEndpointResponse), hwr);
        }

        public void RetrieveTokenEndpointResponse (IAsyncResult rez)
        {
            HttpWebRequest hwr =(HttpWebRequest) rez.AsyncState;
            HttpWebResponse resp =(HttpWebResponse)hwr.EndGetResponse(rez); // ERROR HERE

            StreamReader sr = new StreamReader(resp.GetResponseStream());
            string responseString = sr.ReadToEnd();
            JObject jo = JsonConvert.DeserializeObject(responseString) as JObject;
            myApp.AccessToken = (string)jo["access_token"];


            System.Threading.Thread myThread = new  System.Threading.Thread (() => 
            {
                    ma.myWebView.GoBack ();
            });
            myThread.Start ();
        }

Any suggestions are appreciated. Thanks.

user2625086
  • 221
  • 5
  • 18
  • Try analyzing what is sent with something like http://requestb.in/ or intercept the traffic with fiddler. Also why are you using this nasty old school WebRequest way of communicating when you have HttpClient. The code you have provided can be shortened to less than half... – Cheesebaron Feb 07 '14 at 10:22
  • @Cheesebaron can you please provide me with an example on how to use the 'HttpClient' ? – user2625086 Feb 10 '14 at 07:19

0 Answers0