使用Auth2_access_令牌调用linkedin Restful API时,在android中出现以下错误

使用Auth2_access_令牌调用linkedin Restful API时,在android中出现以下错误,linkedin,linkedin-api,Linkedin,Linkedin Api,401 146286394881 EMUQR2KPUF 0无效访问令牌 我的请求Url是: “+accesstoken 如果有人遇到这个问题,请提出建议。还有,为LinkedIN生成Auth2访问令牌的正确方法是什么 第1步: 按照以下步骤向linkedIn注册你的应用程序。然后获取你的api_密钥和api_密钥 第二步: public class MainActivity extends Activity { /*CONSTANT FOR THE AUTHORIZATION PROCESS*

401 146286394881 EMUQR2KPUF 0无效访问令牌

我的请求Url是:

“+accesstoken


如果有人遇到这个问题,请提出建议。还有,为LinkedIN生成Auth2访问令牌的正确方法是什么

第1步: 按照以下步骤向linkedIn注册你的应用程序。然后获取你的api_密钥和api_密钥

第二步:

public class MainActivity extends Activity {

/*CONSTANT FOR THE AUTHORIZATION PROCESS*/

/****FILL THIS WITH YOUR INFORMATION*********/
//This is the public api key of our application
private static final String API_KEY = "YOUR_API_KEY";
//This is the private api key of our application
private static final String SECRET_KEY = "YOUR_API_SECRET";
//This is any string we want to use. This will be used for avoid CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "E3ZYKC1T6H2yP4z";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases. 
private static final String REDIRECT_URI = "http://com.amalbit.redirecturl";
/*********************************************/

//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/uas/oauth2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE ="code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";

private WebView webView;
private ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //get the webView from the layout
    webView = (WebView) findViewById(R.id.main_activity_web_view);

    //Request focus for the webview
    webView.requestFocus(View.FOCUS_DOWN);

    //Show a progress dialog to the user
    pd = ProgressDialog.show(this, "", this.getString(R.string.loading),true);

    //Set a custom web view client
    webView.setWebViewClient(new WebViewClient(){
          @Override
          public void onPageFinished(WebView view, String url) {
                //This method will be executed each time a page finished loading.
                //The only we do is dismiss the progressDialog, in case we are showing any.
              if(pd!=null && pd.isShowing()){
                  pd.dismiss();
              }
          }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl) {
            //This method will be called when the Auth proccess redirect to our RedirectUri.
            //We will check the url looking for our RedirectUri.
            if(authorizationUrl.startsWith(REDIRECT_URI)){
                Log.i("Authorize", "");
                Uri uri = Uri.parse(authorizationUrl);
                //We take from the url the authorizationToken and the state token. We have to check that the state token returned by the Service is the same we sent.
                //If not, that means the request may be a result of CSRF and must be rejected.
                String stateToken = uri.getQueryParameter(STATE_PARAM);
                if(stateToken==null || !stateToken.equals(STATE)){
                    Log.e("Authorize", "State token doesn't match");
                    return true;
                }

                //If the user doesn't allow authorization to our application, the authorizationToken Will be null.
                String authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE);
                if(authorizationToken==null){
                    Log.i("Authorize", "The user doesn't allow authorization.");
                    return true;
                }
                Log.i("Authorize", "Auth token received: "+authorizationToken);

                //Generate URL for requesting Access Token
                String accessTokenUrl = getAccessTokenUrl(authorizationToken);
                //We make the request in a AsyncTask
                new PostRequestAsyncTask().execute(accessTokenUrl);

            }else{
                //Default behaviour
                Log.i("Authorize","Redirecting to: "+authorizationUrl);
                webView.loadUrl(authorizationUrl);
            }
            return true;
        }
    });

    //Get the authorization Url
    String authUrl = getAuthorizationUrl();
    Log.i("Authorize","Loading Auth Url: "+authUrl);
    //Load the authorization URL into the webView
    webView.loadUrl(authUrl);
}

/**
 * Method that generates the url for get the access token from the Service
 * @return Url
 */
private static String getAccessTokenUrl(String authorizationToken){
    return ACCESS_TOKEN_URL
            +QUESTION_MARK
            +GRANT_TYPE_PARAM+EQUALS+GRANT_TYPE
            +AMPERSAND
            +RESPONSE_TYPE_VALUE+EQUALS+authorizationToken
            +AMPERSAND
            +CLIENT_ID_PARAM+EQUALS+API_KEY
            +AMPERSAND
            +REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI
            +AMPERSAND
            +SECRET_KEY_PARAM+EQUALS+SECRET_KEY;
}
/**
 * Method that generates the url for get the authorization token from the Service
 * @return Url
 */
private static String getAuthorizationUrl(){
    return AUTHORIZATION_URL
            +QUESTION_MARK+RESPONSE_TYPE_PARAM+EQUALS+RESPONSE_TYPE_VALUE
            +AMPERSAND+CLIENT_ID_PARAM+EQUALS+API_KEY
            +AMPERSAND+STATE_PARAM+EQUALS+STATE
            +AMPERSAND+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class PostRequestAsyncTask extends AsyncTask<String, Void, Boolean>{

    @Override
    protected void onPreExecute(){
        pd = ProgressDialog.show(MainActivity.this, "", MainActivity.this.getString(R.string.loading),true);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        if(urls.length>0){
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(url);
            try{
                HttpResponse response = httpClient.execute(httpost);
                if(response!=null){
                    //If status is OK 200
                    if(response.getStatusLine().getStatusCode()==200){
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        JSONObject resultJson = new JSONObject(result);
                        //Extract data from JSON Response
                        int expiresIn = resultJson.has("expires_in") ? resultJson.getInt("expires_in") : 0;

                        String accessToken = resultJson.has("access_token") ? resultJson.getString("access_token") : null;
                        Log.e("Tokenm", ""+accessToken);
                        if(expiresIn>0 && accessToken!=null){
                            Log.i("Authorize", "This is the access Token: "+accessToken+". It will expires in "+expiresIn+" secs");

                            //Calculate date of expiration
                            Calendar calendar = Calendar.getInstance();
                            calendar.add(Calendar.SECOND, expiresIn);
                            long expireDate = calendar.getTimeInMillis();

                            ////Store both expires in and access token in shared preferences
                            SharedPreferences preferences = MainActivity.this.getSharedPreferences("user_info", 0);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putLong("expires", expireDate);
                            editor.putString("accessToken", accessToken);
                            editor.commit();

                            return true;
                        }
                    }
                }
            }catch(IOException e){
                Log.e("Authorize","Error Http response "+e.getLocalizedMessage());  
            }
            catch (ParseException e) {
                Log.e("Authorize","Error Parsing Http response "+e.getLocalizedMessage());
            } catch (JSONException e) {
                Log.e("Authorize","Error Parsing Http response "+e.getLocalizedMessage());
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean status){
        if(pd!=null && pd.isShowing()){
            pd.dismiss();
        }
        if(status){
            //If everything went Ok, change to another activity.
            Intent startProfileActivity = new Intent(MainActivity.this, ProfileActivity.class);
            MainActivity.this.startActivity(startProfileActivity);
        }
    }

};
}
main活动:

public class MainActivity extends Activity {

/*CONSTANT FOR THE AUTHORIZATION PROCESS*/

/****FILL THIS WITH YOUR INFORMATION*********/
//This is the public api key of our application
private static final String API_KEY = "YOUR_API_KEY";
//This is the private api key of our application
private static final String SECRET_KEY = "YOUR_API_SECRET";
//This is any string we want to use. This will be used for avoid CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "E3ZYKC1T6H2yP4z";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases. 
private static final String REDIRECT_URI = "http://com.amalbit.redirecturl";
/*********************************************/

//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/uas/oauth2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE ="code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";

private WebView webView;
private ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //get the webView from the layout
    webView = (WebView) findViewById(R.id.main_activity_web_view);

    //Request focus for the webview
    webView.requestFocus(View.FOCUS_DOWN);

    //Show a progress dialog to the user
    pd = ProgressDialog.show(this, "", this.getString(R.string.loading),true);

    //Set a custom web view client
    webView.setWebViewClient(new WebViewClient(){
          @Override
          public void onPageFinished(WebView view, String url) {
                //This method will be executed each time a page finished loading.
                //The only we do is dismiss the progressDialog, in case we are showing any.
              if(pd!=null && pd.isShowing()){
                  pd.dismiss();
              }
          }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl) {
            //This method will be called when the Auth proccess redirect to our RedirectUri.
            //We will check the url looking for our RedirectUri.
            if(authorizationUrl.startsWith(REDIRECT_URI)){
                Log.i("Authorize", "");
                Uri uri = Uri.parse(authorizationUrl);
                //We take from the url the authorizationToken and the state token. We have to check that the state token returned by the Service is the same we sent.
                //If not, that means the request may be a result of CSRF and must be rejected.
                String stateToken = uri.getQueryParameter(STATE_PARAM);
                if(stateToken==null || !stateToken.equals(STATE)){
                    Log.e("Authorize", "State token doesn't match");
                    return true;
                }

                //If the user doesn't allow authorization to our application, the authorizationToken Will be null.
                String authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE);
                if(authorizationToken==null){
                    Log.i("Authorize", "The user doesn't allow authorization.");
                    return true;
                }
                Log.i("Authorize", "Auth token received: "+authorizationToken);

                //Generate URL for requesting Access Token
                String accessTokenUrl = getAccessTokenUrl(authorizationToken);
                //We make the request in a AsyncTask
                new PostRequestAsyncTask().execute(accessTokenUrl);

            }else{
                //Default behaviour
                Log.i("Authorize","Redirecting to: "+authorizationUrl);
                webView.loadUrl(authorizationUrl);
            }
            return true;
        }
    });

    //Get the authorization Url
    String authUrl = getAuthorizationUrl();
    Log.i("Authorize","Loading Auth Url: "+authUrl);
    //Load the authorization URL into the webView
    webView.loadUrl(authUrl);
}

/**
 * Method that generates the url for get the access token from the Service
 * @return Url
 */
private static String getAccessTokenUrl(String authorizationToken){
    return ACCESS_TOKEN_URL
            +QUESTION_MARK
            +GRANT_TYPE_PARAM+EQUALS+GRANT_TYPE
            +AMPERSAND
            +RESPONSE_TYPE_VALUE+EQUALS+authorizationToken
            +AMPERSAND
            +CLIENT_ID_PARAM+EQUALS+API_KEY
            +AMPERSAND
            +REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI
            +AMPERSAND
            +SECRET_KEY_PARAM+EQUALS+SECRET_KEY;
}
/**
 * Method that generates the url for get the authorization token from the Service
 * @return Url
 */
private static String getAuthorizationUrl(){
    return AUTHORIZATION_URL
            +QUESTION_MARK+RESPONSE_TYPE_PARAM+EQUALS+RESPONSE_TYPE_VALUE
            +AMPERSAND+CLIENT_ID_PARAM+EQUALS+API_KEY
            +AMPERSAND+STATE_PARAM+EQUALS+STATE
            +AMPERSAND+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class PostRequestAsyncTask extends AsyncTask<String, Void, Boolean>{

    @Override
    protected void onPreExecute(){
        pd = ProgressDialog.show(MainActivity.this, "", MainActivity.this.getString(R.string.loading),true);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        if(urls.length>0){
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpost = new HttpPost(url);
            try{
                HttpResponse response = httpClient.execute(httpost);
                if(response!=null){
                    //If status is OK 200
                    if(response.getStatusLine().getStatusCode()==200){
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        JSONObject resultJson = new JSONObject(result);
                        //Extract data from JSON Response
                        int expiresIn = resultJson.has("expires_in") ? resultJson.getInt("expires_in") : 0;

                        String accessToken = resultJson.has("access_token") ? resultJson.getString("access_token") : null;
                        Log.e("Tokenm", ""+accessToken);
                        if(expiresIn>0 && accessToken!=null){
                            Log.i("Authorize", "This is the access Token: "+accessToken+". It will expires in "+expiresIn+" secs");

                            //Calculate date of expiration
                            Calendar calendar = Calendar.getInstance();
                            calendar.add(Calendar.SECOND, expiresIn);
                            long expireDate = calendar.getTimeInMillis();

                            ////Store both expires in and access token in shared preferences
                            SharedPreferences preferences = MainActivity.this.getSharedPreferences("user_info", 0);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putLong("expires", expireDate);
                            editor.putString("accessToken", accessToken);
                            editor.commit();

                            return true;
                        }
                    }
                }
            }catch(IOException e){
                Log.e("Authorize","Error Http response "+e.getLocalizedMessage());  
            }
            catch (ParseException e) {
                Log.e("Authorize","Error Parsing Http response "+e.getLocalizedMessage());
            } catch (JSONException e) {
                Log.e("Authorize","Error Parsing Http response "+e.getLocalizedMessage());
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean status){
        if(pd!=null && pd.isShowing()){
            pd.dismiss();
        }
        if(status){
            //If everything went Ok, change to another activity.
            Intent startProfileActivity = new Intent(MainActivity.this, ProfileActivity.class);
            MainActivity.this.startActivity(startProfileActivity);
        }
    }

};
}
公共类MainActivity扩展活动{
/*用于授权过程的常量*/
/****把你的信息填在这里*********/
//这是我们应用程序的公共api密钥
私有静态最终字符串API\u KEY=“您的API\u KEY”;
//这是我们应用程序的私有api密钥
私有静态最终字符串SECRET\u KEY=“YOUR\u API\u SECRET”;
//这是我们要使用的任何字符串。这将用于避免CSRF攻击。您可以在此处生成一个字符串:http://strongpasswordgenerator.com/
私有静态最终字符串状态=“E3ZYKC1T6H2yP4z”;
//这是LinkedIn身份验证过程将重定向到的url。我们可以放置以http://或https://开头的任何内容。
//我们使用了一个虚构的url,在重定向时我们将拦截它。避免大写。
私有静态最终字符串重定向_URI=”http://com.amalbit.redirecturl";
/*********************************************/
//这些是用于构建URL的常量
私有静态最终字符串授权\u URL=”https://www.linkedin.com/uas/oauth2/authorization";
私有静态最终字符串访问\u令牌\u URL=”https://www.linkedin.com/uas/oauth2/accessToken";
私有静态最终字符串SECRET\u KEY\u PARAM=“client\u SECRET”;
私有静态最终字符串响应类型参数=“响应类型”;
私有静态最终字符串GRANT\u TYPE\u PARAM=“GRANT\u TYPE”;
私有静态最终字符串GRANT_TYPE=“authorization_code”;
私有静态最终字符串响应\u TYPE\u VALUE=“code”;
私有静态最终字符串CLIENT_ID_PARAM=“CLIENT_ID”;
私有静态最终字符串状态_PARAM=“STATE”;
私有静态最终字符串REDIRECT\u URI\u PARAM=“REDIRECT\u URI”;
/*---------------------------------------*/
私有静态最终字符串问号=“?”;
专用静态最终字符串和“&”;
私有静态最终字符串等于=“=”;
私有网络视图;
私营部门;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//从布局中获取webView
webView=(webView)findViewById(R.id.main\u activity\u web\u view);
//请求webview的焦点
webView.requestFocus(View.FOCUS\u向下);
//向用户显示进度对话框
pd=ProgressDialog.show(this,”,this.getString(R.string.loading),true);
//设置自定义web视图客户端
setWebViewClient(新的WebViewClient(){
@凌驾
公共void onPageFinished(WebView视图,字符串url){
//每次页面加载完成时都将执行此方法。
//我们唯一要做的就是关闭progressDialog,以防出现任何问题。
if(pd!=null&&pd.isShowing()){
pd.解散();
}
}
@凌驾
公共布尔值shouldOverrideUrlLoading(WebView视图,字符串授权URL){
//当Auth进程重定向到我们的重定向URI时,将调用此方法。
//我们将检查url以查找重定向URI。
if(authorizationUrl.startsWith(重定向URI)){
Log.i(“授权”、“授权”);
Uri=Uri.parse(authorizationUrl);
//我们从url获取authorizationToken和state token。我们必须检查服务返回的state token是否与我们发送的相同。
//如果不是,这意味着该请求可能是CSRF的结果,必须予以拒绝。
字符串stateToken=uri.getQueryParameter(STATE_PARAM);
如果(stateToken==null | |!stateToken.equals(STATE)){
Log.e(“授权”,“状态令牌不匹配”);
返回true;
}
//如果用户不允许对我们的应用程序进行授权,则authorizationToken将为null。
String authorizationToken=uri.getQueryParameter(响应类型值);
if(authorizationToken==null){
Log.i(“授权”,“用户不允许授权”);
返回true;
}
Log.i(“授权”,“收到授权令牌:”+authorizationToken);
//生成请求访问令牌的URL
字符串accessTokenUrl=getAccessTokenUrl(authorizationToken);
//我们在异步任务中发出请求
新建PostRequestAsyncTask().execute(accessTokenUrl);
}否则{
//违约行为
Log.i(“授权”,“重定向到:”+authorizationUrl);
loadUrl(授权URL);
}
返回true;
}
});
//获取授权Url
字符串authUrl=getAuthorizationUrl();
Log.i(“授权”,“加载验证Url:+authUrl”);
//将授权URL加载到webView中
loadUrl(authUrl);
}
/**
*方法,该方法生成用于从服务获取访问令牌的url
*@returnurl
*/
私有静态字符串getAccessTokenUrl(字符串授权令牌){
返回访问\u令牌\u URL
+问号
+授予类型参数+等于+授予类型
+符号
+响应类型值+等于+授权令牌
+符号
+客户端ID参数+等于+API密钥
+符号
+重定向URI参数+等于+重定向URI
+符号
+秘密密钥参数+等于+秘密密钥