1. 程式人生 > >.net c#後臺請求介面

.net c#後臺請求介面

我們在請求介面的時候,有時因為跨域的問題,總是請求介面失敗,亦或是請求介面時,頁面還存在跳轉的問題,這個時候,我們通過前臺ajax請求自己的一般處理程式,用一般處理程式請求客戶提供的介面

    //獲取token
    public string gettoken(HttpContext context)
    {
       string strResult = "";
        try
        {
            string code = context.Request.QueryString["code"];
            string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("userName" + ":" + "pwd"));  //驗證使用者的身份,否則會報401(未授權)的錯誤,
            LogHelper.WriteLog(code);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://vcc.hbasesoft.com:8162/oauth/token?client_id=69D8274D631711E880ADDF64DF6ADFSD&code=" + code + "&grant_type=authorization_code&scope=read write&redirect_uri=http://218.194.184.150:5901/versioninfo.html");
            myRequest.Method = "POST";
            myRequest.ContentType = "text/xml";
            myRequest.Headers.Add("Authorization: " + " Basic " + user);//新增驗證頭
            try
            {
                HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }
                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {
                strResult = "error:" + exp.Message;
                LogHelper.WriteLog(strResult);
            }
        }
        catch (Exception exp)
        {
            strResult = "error:" + exp.Message;
            LogHelper.WriteLog(strResult);
        }

        return strResult;
    }