private Token requestToken ( String url ) throws OAuthTokenException , JSONSerializerException , HttpClientException , URISyntaxException , InvalidRequestException { // Create the request and send it to get the response/token. HttpRequest request = new HttpRequest ( ) ; request . setUri ( new URI ( url ) ) ; request . setMethod ( HttpMethod . POST ) ; request . setHeaders ( new HashMap < String , String > ( ) ) ; request . getHeaders ( ) . put ( "Content-Type" , "application/x-www-form-urlencoded" ) ; HttpResponse response = httpClient . request ( request ) ; // Create a map of the response InputStream inputStream = response . getEntity ( ) . getContent ( ) ; Map < String , Object > map = jsonSerializer . deserializeMap ( inputStream ) ; httpClient . releaseConnection ( ) ; // Check for a error response and throw it. if ( response . getStatusCode ( ) != 200 && map . get ( "error" ) != null ) { String errorType = map . get ( "error" ) . toString ( ) ; String errorDescription = map . get ( "message" ) == null ? "" : ( String ) map . get ( "message" ) ; if ( "invalid_request" . equals ( errorType ) ) { throw new InvalidTokenRequestException ( errorDescription ) ; } else if ( "invalid_client" . equals ( errorType ) ) { throw new InvalidOAuthClientException ( errorDescription ) ; } else if ( "invalid_grant" . equals ( errorType ) ) { throw new InvalidOAuthGrantException ( errorDescription ) ; } else if ( "unsupported_grant_type" . equals ( errorType ) ) { throw new UnsupportedOAuthGrantTypeException ( errorDescription ) ; } else { throw new OAuthTokenException ( errorDescription ) ; } } // Another error by not getting a 200 result else if ( response . getStatusCode ( ) != 200 ) { throw new OAuthTokenException ( "Token request failed with http error code: " + response . getStatusCode ( ) ) ; } // Create a token based on the response Token token = new Token ( ) ; Object tempObj = map . get ( "access_token" ) ; token . setAccessToken ( tempObj == null ? "" : ( String ) tempObj ) ; tempObj = map . get ( "token_type" ) ; token . setTokenType ( tempObj == null ? "" : ( String ) tempObj ) ; tempObj = map . get ( "refresh_token" ) ; token . setRefreshToken ( tempObj == null ? "" : ( String ) tempObj ) ; Long expiresIn ; try { expiresIn = Long . parseLong ( String . valueOf ( map . get ( "expires_in" ) ) ) ; } catch ( NumberFormatException nfe ) { expiresIn = 0L ; } token . setExpiresInSeconds ( expiresIn ) ; return token ; }
Request a token .