简体   繁体   中英

The remote server returned an error: (401) Unauthorized

I'm trying to get the access token from the windows live connect api by using this code

string requestUrl = "https://consent.live.com/AccessToken.aspx";

        // Request the access token.
        string postData = string.Format("{0}?wrap_client_id={1}&wrap_client_secret={2}&wrap_callback={3}&wrap_verification_code={4}&idtype={5}",
                requestUrl,
               "000000004C039809",
                "l4VJekL1vFL1iFVmcP5qLkWv9ukY4mdl",
                "http://ewshops.com",
                "dac5d71d-d640-30d1-ebed-3576b132b3ec",
                "cid");
        byte[] postDataEncoded = System.Text.Encoding.UTF8.GetBytes(postData);

        WebRequest req = HttpWebRequest.Create(requestUrl);
        req.Method = "POST";
       // req.
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = postDataEncoded.Length;


        Stream requestStream = req.GetRequestStream();
        requestStream.Write(postDataEncoded, 0, postDataEncoded.Length);

        WebResponse res = req.GetResponse();

        string responseBody = null;

        using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
        {
            responseBody = sr.ReadToEnd();
        }

        // Process FORM POST.
        NameValueCollection responseCollection = System.Web.HttpUtility.ParseQueryString(responseBody);

        return responseCollection["wrap_access_token"];

but I've recieved the following error

The remote server returned an error: (401) Unauthorized.

Show us the response body, it usually contains more information. You should also urlencode http://ewshops.com before adding it to the uri.

I had the same problem and fixed it as follows. Remove the requestUrl ("https://consent.live.com/AccessToken.aspx") and the subsequent "?" from your postData. The POST data should be in x-www-form-urlencoded format and that does not include the request URL. Also HttpUtility.UrlEncode() all the parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM