Skip to content

Instantly share code, notes, and snippets.

@mariofts
Last active August 29, 2015 13:56
Show Gist options
  • Save mariofts/9123378 to your computer and use it in GitHub Desktop.
Save mariofts/9123378 to your computer and use it in GitHub Desktop.
TestaOAuth2
package br.com.caelum.livraria.rest;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
public class TestaOAuth2 {
public static void main(String[] args) throws Exception {
String tokenEndpoint = "http://fj36webservicerest-oauthserver.herokuapp.com/oauth/token";
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(tokenEndpoint)
.setGrantType(GrantType.PASSWORD)
.setClientId("oauth2_client_id")
.setClientSecret("oauth2_client_secret")
.setUsername("fake_user")
.setPassword("passwd")
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse oauthResponse = oAuthClient.accessToken(request);
System.out.println("Access token: " + oauthResponse.getAccessToken());
System.out.println("Expira em: " + oauthResponse.getExpiresIn());
//acessando o sistema de pagamento com o token obtido
Client client = ClientBuilder.newClient();
WebTarget target = client .target(new URI(
"http://fj36webservicerest-seguro.herokuapp.com/v1/pagamento/1"
));
String entity = target.request(MediaType.APPLICATION_XML_TYPE)
.header("Authorization",
"Bearer " + oauthResponse.getAccessToken())
.get(String.class);
System.out.println("Resposta: " + entity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment