如何使用java创建一个oAuth请求?

前端之家收集整理的这篇文章主要介绍了如何使用java创建一个oAuth请求?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要使用oAuth与 Viagogo website连接.参考他们的 documentation,我需要创建一个类似于以下的请求
Using the example in step 1A,this means you may generate a signature base string that looks like the following:

GET&http%3A%2F%2Fapi.viagogo.net%2FPublic%2FSimpleOAuthAccessRequest&oauth_consumer_key%3Dtestkey%26oauth_nonce%3Dmyn0nc3%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1292404912%26oauth_version%3D1.0%26scope%3DAPI.Public

我使用以下代码,但是当我评论行1,2它返回未经授权的错误,当我使用它,它显示oauthService.signRequest返回void.

TradeKingAPI.java

import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;

public class TradeKingAPI extends DefaultApi10a {
    @Override
    public String getRequestTokenEndpoint() {
        return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest";
    }
    @Override
    public String getAccessTokenEndpoint() {
        return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest";
    }
    @Override
    public String getAuthorizationUrl(Token requestToken) {
        return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest";
    }
}

main.java

import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

import api.TradeKingAPI;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.OAuthConstants;
import org.scribe.oauth.OAuthService;

   ........

    OAuthService oauthService = new ServiceBuilder()
            .provider(TradeKingAPI.class)
            .apiKey("My consumer key")
            .apiSecret("My secret")
            .scope("API.Public")
            .build();

    Long seconds = (System.currentTimeMillis() / 1000);
    System.out.println(">>>" + seconds);
    String stSeconds = seconds.toString();
    OAuthRequest request = new OAuthRequest(Verb.GET,"http://api.viagogo.net/Public
                                                                     /SimpleOAuthAccessRequest");

    request.addOAuthParameter(OAuthConstants.CONSUMER_KEY,"My consumer key");
    request.addOAuthParameter(OAuthConstants.NONCE,"myn0nc3");
    request.addOAuthParameter(OAuthConstants.SIGN_METHOD,"HMAC-SHA1");
    request.addOAuthParameter(OAuthConstants.TIMESTAMP,seconds.toString());
    request.addOAuthParameter(OAuthConstants.VERSION,"1.0");
    request.addOAuthParameter("scope","API.Public");

 1  String signature = oauthService.signRequest(OAuthConstants.EMPTY_TOKEN,request);

 2  request.addOAuthParameter(OAuthConstants.SIGNATURE,signature);
    Response response = request.send();
    System.err.println(">>" + response.isSuccessful());
    System.err.println(">>" + response.getMessage());
    System.err.println(">>" + response.getBody());

解决方法

从我从Viagogo公共API访问文档中了解到,您在步骤1中获得的令牌相当于完整的OAuth 1.0a“舞蹈”中的请求令牌.

所以,你应该可以使用scribe-java内部类来获取这个令牌,而不用手动.唯一的区别是,在抄写员中,此请求还向OAuth服务器发送一个回呼URL,用于OAuth“舞蹈”的下一步.

由于我无法获得消费者帐户,我只能在此做出假设.所以我们有两种情况:

情况1:Viagogo服务器容忍额外的参数(即回叫URL)

所以你可以用这个代码

import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;

public class TradeKingAPI extends DefaultApi10a {

    @Override
    public Verb getRequestTokenVerb()
    {
      return Verb.GET;
    }

    @Override
    public String getRequestTokenEndpoint() {
        return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest";
    }

    @Override
    public String getAccessTokenEndpoint() {
        return "none";
    }

    @Override
    public String getAuthorizationUrl(Token requestToken) {
        return "none";
    }
}

那么你的呼叫代码将是:

OAuthService service = new ServiceBuilder()
                            .provider(TradeKingAPI.class)
                            .signatureType(QueryString)
                            .apiKey("My consumer key")
                            .apiSecret("My secret")
                            .scope("API.Public")
                            .build();

Token requestToken = service.getRequestToken();

//make your API calls

OAuthRequest request = new OAuthRequest(Verb.GET,"http://api.viagogo.net/Public/Event/235");
service.signRequest(requestToken,request);
Response response = request.send();
System.out.println(response.getBody());

但是正如我所说,如果Viagogo安全性有点严格,并且拒绝无用的参数oauth_callback,则需要切换到方案2

情景2:建立自己的OAuthService

在这种情况下,您必须创建一个新的OAuthService,以避免处理OAuthCallback参数.

import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.*;
import org.scribe.oauth.OAuth10aServiceImpl;

import java.util.Map;

public class OAuth10aServiceForViagogo extends OAuth10aServiceImpl {

    private OAuthConfig config;
    private DefaultApi10a api;

    public OAuth10aServiceForViagogo(DefaultApi10a api,OAuthConfig config) {
        super(api,config);

        this.api = api;
        this.config = config;
    }

    private void addOAuthParams(OAuthRequest request,Token token) {
        request.addOAuthParameter(OAuthConstants.TIMESTAMP,api.getTimestampService().getTimestampInSeconds());
        request.addOAuthParameter(OAuthConstants.NONCE,api.getTimestampService().getNonce());
        request.addOAuthParameter(OAuthConstants.CONSUMER_KEY,config.getApiKey());
        request.addOAuthParameter(OAuthConstants.SIGN_METHOD,api.getSignatureService().getSignatureMethod());
        request.addOAuthParameter(OAuthConstants.VERSION,getVersion());
        request.addOAuthParameter(OAuthConstants.SCOPE,config.getScope());
        request.addOAuthParameter(OAuthConstants.SIGNATURE,getSignature(request,token));

    }

    private String getSignature(OAuthRequest request,Token token) {

        String baseString = api.getBaseStringExtractor().extract(request);
        String signature = api.getSignatureService().getSignature(baseString,config.getApiSecret(),token.getSecret());

        return signature;
    }

    private void appendSignature(OAuthRequest request) {
        for (Map.Entry<String,String> entry : request.getOauthParameters().entrySet()) {
            request.addQuerystringParameter(entry.getKey(),entry.getValue());
        }
    }

    @Override
    public Token getRequestToken(RequestTuner tuner) {
        OAuthRequest request = new OAuthRequest(api.getRequestTokenVerb(),api.getRequestTokenEndpoint());

        addOAuthParams(request,OAuthConstants.EMPTY_TOKEN);
        appendSignature(request);

        Response response = request.send(tuner);
        String body = response.getBody();

        return api.getRequestTokenExtractor().extract(body);
    }
}

调用createService时,TrakingApi类将略有不同,以创建一个OAuth10aServiceForViagogo:

import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;

public class TradeKingAPI extends DefaultApi10a {

    @override
    public OAuthService createService(OAuthConfig config)
    {
      return new OAuth10aServiceForViagogo(this,config);
    }

    @Override
    public Verb getRequestTokenVerb()
    {
      return Verb.GET;
    }

    @Override
    public String getRequestTokenEndpoint() {
        return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest";
    }

    @Override
    public String getAccessTokenEndpoint() {
        return "none";
    }

    @Override
    public String getAuthorizationUrl(Token requestToken) {
        return "none";
    }
}

那么你的通话代码将是一样的:

OAuthService service = new ServiceBuilder()
                                .provider(TradeKingAPI.class)
                                .signatureType(QueryString)
                                .apiKey("My consumer key")
                                .apiSecret("My secret")
                                .scope("API.Public")
                                .build();

    Token requestToken = service.getRequestToken();

    //make your API calls

    OAuthRequest request = new OAuthRequest(Verb.GET,"http://api.viagogo.net/Public/Event/235");
    service.signRequest(requestToken,request);
    Response response = request.send();
    System.out.println(response.getBody());

我没有测试所有这些代码,因为我不能访问消费者和秘密密钥,但它应该接近你所需要的.

原文链接:https://www.f2er.com/java/121163.html

猜你在找的Java相关文章