繁体   English   中英

WebRequest 400对API的错误请求

[英]WebRequest 400 bad request to api

我正在对instagram api发出webrequest,并收到400个错误请求,但是我想这不是instagram特有的,是我代码中的一般错误。 这是我的代码。此请求中的“代码”参数是从上一个请求中获取的。代码在“ GetResponse”方法处中断

  string clientID = "myclientid";
  string clientsecret="myclientsecret";
  string redirectURL = "http://localhost:64341/"; 
 string webrequestUri = "https://api.instagram.com/oauth/
  access_token?  client_id=" + clientID + "&client_secret=
  " + clientsecret +   "&grant_type=authorization_code"                                            + "&redirect_uri="redirectURL+"&code="
+Request.QueryString["code"].ToString();
WebRequest request = WebRequest.Create(webrequestUri);
request.Method = "POST";
WebResponse response = request.GetResponse();

C#/ asp.net工作示例:

namespace InstagramLogin.Code
{
    public class InstagramAuth
    {
        private InstagramClient myApp = new InstagramClient();

        public string genUserAutorizationUrl()
        {
            return String.Format(myApp.OAuthAutorizeURL, myApp.ClientId, myApp.RedirectUri);
        }

        public AuthUserApiToken getTokenId(string CODE)
        {
            //curl \-F 'client_id=CLIENT-ID' \
            //-F 'client_secret=CLIENT-SECRET' \
            //-F 'grant_type=authorization_code' \
            //-F 'redirect_uri=YOUR-REDIRECT-URI' \
            //-F 'code=CODE' \https://api.instagram.com/oauth/access_token

            var wc = new WebClient();
            var wcResponse = wc.UploadValues(myApp.AuthAccessTokenUrl, 
                                new System.Collections.Specialized.NameValueCollection() { 
                                    { "client_id", myApp.ClientId }, 
                                    { "client_secret", myApp.ClientSecret },
                                    { "grant_type", "authorization_code"},
                                    { "redirect_uri", myApp.RedirectUri},
                                    { "code", CODE}
                                });
            var decodedResponse = wc.Encoding.GetString(wcResponse);
            AuthUserApiToken UserApiToken = JsonConvert.DeserializeObject<AuthUserApiToken>(decodedResponse);

            return UserApiToken;
        }
    }
}

您的对象:

    namespace InstagramLogin.Code
    {
    public class InstagramClient
        {

            private const string ApiUriDefault = "https://api.instagram.com/v1/";
            private const string OAuthUriDefault = "https://api.instagram.com/oauth/";
            private const string RealTimeApiDefault = "https://api.instagram.com/v1/subscriptions/";

            private const string OAuthAutorizeURLDefault = "https://api.instagram.com/oauth/authorize/?client_id={0}&redirect_uri={1}&response_type=code";
            private const string AuthAccessTokenUrlDefault = "https://api.instagram.com/oauth/access_token";

            private const string clientId = "clientid";
            private const string clientSecretId = "clientsecretid";
            private const string redirectUri = "http://localhost/InstagramLogin/InstaAuth.aspx";
            private const string websiteUri = "http://localhost/InstagramLogin/InstaAuth.aspx";

            public string ApiUri { get; set; }
            public string OAuthUri { get; set; }
            public string RealTimeApi { get; set; }


            public string OAuthAutorizeURL { get { return OAuthAutorizeURLDefault; } }
            public string ClientId { get { return clientId; } }
            public string ClientSecret { get { return clientSecretId; } }
            public string RedirectUri { get { return redirectUri; } }
            public string AuthAccessTokenUrl { get { return AuthAccessTokenUrlDefault; } }
//removed props
    }
    }

instagram登录的用户:

namespace InstagramLogin.Code
{
    public class SessionInstaAuthUser
    {

            public bool isInSession()
            {
                return HttpContext.Current.Session["AuthUserApiToken"] != null;
            }

            public AuthUserApiToken get()
            {
                if (isInSession())
                {
                    return HttpContext.Current.Session["AuthUserApiToken"] as AuthUserApiToken;
                }
                return null;
            }

            public void set(AuthUserApiToken value)
            {
                HttpContext.Current.Session["AuthUserApiToken"] = value;
            }

            public void clear()
            {
                if (isInSession())
                {
                    HttpContext.Current.Session["AuthUserApiToken"] = null;
                }
            }

    }
}

标记:

<asp:Button ID="btnInstaAuth"
        Text="Click here to get instagram auth"
        runat="server" />

后面的代码:

//objects
private InstagramClient InstagramApiCLient = new InstagramClient();
        private InstagramAuth AuthManager = new InstagramAuth();
        private SessionInstaAuthUser SesssionInstaUser = new SessionInstaAuthUser();

//单击带有测试的登录-用户已登录(会话中)

void btnInstaAuth_Click(Object sender,
                               EventArgs e)
        {
            btnGetInstaPosts.Visible = false;
            if (SesssionInstaUser.isInSession())
            {
                SesssionInstaUser.clear();
                Button clickedButton = (Button)sender;
                clickedButton.Text = "Click here to get instagram auth";
                btnInstaAuth.Visible = true;
            }
            else
            {
                Response.Redirect(AuthManager.genUserAutorizationUrl());
            }
        }

您可以在此类InstagramAuthAuth中找到所需的内容。对不起,如果我确实删除了一些其他方法或属性,请删除它。

此按钮可以在所有页面上使用,仍然不要忘记在instagram设置为登录页面的页面上添加页面负载,查询字符串解析:

//here you read the token instagram generated and append it to the session, or get the error :) 

    if (!IsPostBack)
                {
                    if (!SesssionInstaUser.isInSession())
                    {
                        if (Request.QueryString["code"] != null)
                        {


                            var token = AuthManager.getTokenId(Request.QueryString["code"]);
                            SesssionInstaUser.set(token);
                            //set login button to have option to log out
                            btnInstaAuth.Text = token.user.username + " leave instagtam oAuth";
                            Response.Redirect(Request.Url.ToString().Split('?')[0]);
                    }
                    else
                        if (Request.QueryString["error"] != null)
                        {
                            btnInstaAuth.Text = Request.QueryString["error_description"];
                        }
                }
            }

抱歉,如果我错过了什么,那么在第一堂课中实现php卷曲到c#中。

更新(我确实忘记了一些东西),insta用户obj :)

namespace InstagramLogin.Code
{
    public class UserLogged
    {
        public string id { get; set; }
        public string username { get; set; }
        public string full_name { get; set; }
        public string profile_picture { get; set; }
    }

    public class AuthUserApiToken
    {      
        public string access_token { get; set; }
        public UserLogged user { get; set; }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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