2016-05-26 63 views

回答

1

尝试使用下面的代码与LinkedIn到登录在浏览器中

public class LinkedInActivity extends AppCompatActivity { 
     private String TAG=LinkedInActivity.class.getSimpleName(); 
     public static final String LINKED_IN_PEOPLE_PROFILE = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url)?format=json"; // specific basic details 
     private static final String API_KEY = "Your Client Key"; 
     //This is the private api key of our application 
     private static final String SECRET_KEY = "Your Client Secret Key"; 
     //This is any string of your choice we can use. 
     private static final String STATE = "My String value"; 
     //This is the url that LinkedIn Auth 2.0 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 = "Your OAuth 2.0 redirect URL in"; 
     private String accessToken=""; 
     //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, webView1; 
     private ProgressDialog pd; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_linked_in); 
      //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, "", "Loading...", true); 
      //Set a custom web view client 
      webView.setWebViewClient(new WebViewClient(){ 
       @Override 
       public void onPageStarted(WebView view, String authorizationUrl, Bitmap favicon) { 
       } 
       @Override 
       public void onPageFinished(WebView view, String url) { 
        if (pd != null && pd.isShowing()) { 
         pd.dismiss(); 
        } 
       } 
       @Override 
       public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl){      
        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; 
     } 
     private class PostRequestAsyncTask extends AsyncTask<String, Void, Boolean> { 
      @Override 
      protected void onPreExecute(){ 
       pd = ProgressDialog.show(LinkedInActivity.this, "", "Loading...",true); 
      } 
      @Override 
      protected Boolean doInBackground(String... urls) { 
       if(urls.length>0){ 
        String url = urls[0]; 
        URL sourceUrl = null; 
        try { 
         sourceUrl = new URL(url); 
        } catch (MalformedURLException e) { 
         e.printStackTrace(); 
        } 
        try{ 
         HttpURLConnection conn = (HttpURLConnection)sourceUrl.openConnection(); 
         conn.setReadTimeout(10000); 
         conn.setConnectTimeout(15000); 
         conn.setRequestMethod("GET"); 
         conn.setDoInput(true); 
         conn.connect(); 
         int responsecode = conn.getResponseCode(); 
         Log.d(TAG, "Response Code is :"+responsecode); 
         if(responsecode == 200){ 
          String result = "", line = ""; 
          InputStream inputStream = conn.getInputStream(); 
          BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
          while((line=br.readLine())!=null) 
          { 
           result = result+line; 
          } 
          //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; 
          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(); 

           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) 
       { 
        Log.e(TAG, "Access Token : "+ accessToken); 
       }         
      } 
     }; 
    } 

* 

activity_linked_in.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <WebView 
     android:id="@+id/main_activity_web_view" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</RelativeLayout> 
+0

我找到了解决办法老大....总之非常感谢你 –

+0

欢迎,如果可能的话更新您的代码,以便它可能对其他人有用。 – Logo