java 如何调用 API (Oauth 1.0)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25418764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:00:30  来源:igfitidea点击:

How to call API (Oauth 1.0)?

javaapioauthintuit-partner-platformreconnect

提问by Sanjaya Pandey

I am trying to call this API (Oauth1.0 standard):

我正在尝试调用此 API(Oauth1.0 标准):

https://appcenter.intuit.com/api/v1/Connection/Reconnect

https://appcenter.intuit.com/api/v1/Connection/Reconnect

And what I am doing is : (It am working on java)

我正在做的是:(它正在处理java)

Base64Encoder baseEncoder = Base64Encoder.getInstance();
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("https://appcenter.intuit.com/api/v1/connection/reconnect");
            StringBuilder headerReq = new StringBuilder();
            headerReq.append("OAuth ");
            headerReq.append("oauth_token=\"").append(OAUTHTOKEN).append("\"");
            headerReq.append(", oauth_consumer_key=\"").append(CUNSUMER_KEY).append("\"");
            headerReq.append(", oauth_signature_method=\"base64\"");
            headerReq.append(", oauth_signature=\"")          .append(baseEncoder.encode(PropsUtil.get(OAUTH_CONSUMER_SECRET).getBytes()))
                    .append(baseEncoder.encode("&".getBytes()))            .append(baseEncoder.encode(symmetricEncrypter.decryptData(OAUTH_TOKEN_SECRET).getBytes())).append("\"");
            headerReq.append(", oauth_version=\"1.0\"");
            httpGet.addHeader("Authorization", headerReq.toString());
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                System.out.println("Responsee::"+ response.getStatusLine());
}

And, the response what I am getting is:

而且,我得到的回应是:

<?xml version="1.0" encoding="utf-8"?>
<PlatformResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://platform.intuit.com/api/v1">
  <ErrorMessage>This API requires Authorization.</ErrorMessage>
  <ErrorCode>22</ErrorCode>

Can you please suggest me what I am missing while creating request for Oauth1.0standard or Please, anyone can provide me the sample code of Oauth1.0request example on that standard.

您能否建议我在创建 Oauth1.0标准请求时缺少什么,或者请任何人向我提供该标准上Oauth1.0请求示例的示例代码。

Thank you very much.

非常感谢你。

回答by Manas Mukherjee

PFB working code. Hope it will be useful.

PFB 工作代码。希望它会很有用。

import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;

import com.intuit.ipp.data.Account;
import com.intuit.ipp.exception.FMSException;
import com.intuit.ipp.net.MethodType;
import com.intuit.ipp.services.DataService;

public class POCWithoutDevkitTest {

    private DataService service;
    private OAuthConsumer oAuthConsumer;
    private static String realmID = null;

    public POCWithoutDevkitTest() {
        realmID = "122294642099";
        String consumerKey = "AAAAA";
        String consumerSecret = "BBBBB";
        String accessToken = "CCCCC";
        String accessTokenSecret = "DDDDD";

        setupContext(consumerKey, consumerSecret, accessToken, accessTokenSecret);
    }

    public void setupContext(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
            this.oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
            oAuthConsumer.setTokenWithSecret(accessToken, accessTokenSecret);
            oAuthConsumer.setSigningStrategy(new AuthorizationHeaderSigningStrategy());
    }

    public void authorize(HttpRequestBase httpRequest) throws FMSException {
        try {
            oAuthConsumer.sign(httpRequest);
        } catch (OAuthMessageSignerException e) {
            throw new FMSException(e);
        } catch (OAuthExpectationFailedException e) {
            throw new FMSException(e);
        } catch (OAuthCommunicationException e) {
            throw new FMSException(e);
        }
    }

    public void executeGetRequest(String customURIString){
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        HttpRequestBase httpRequest = null;
        URI uri = null;

        try {
            uri = new URI(customURIString);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        String methodtype = "GET";

        if (methodtype.equals(MethodType.GET.toString())) {
            httpRequest = new HttpGet(uri);
        }

        httpRequest.addHeader("content-type", "application/xml");
        httpRequest.addHeader("Accept","application/xml");

        try {
            authorize(httpRequest);
        } catch (FMSException e) {
            e.printStackTrace();
        }


        HttpResponse httpResponse = null;
        try {
            HttpHost target = new HttpHost(uri.getHost(), -1, uri.getScheme());
            httpResponse = client.execute(target, httpRequest);
            System.out.println("Connection status : " + httpResponse.getStatusLine());

            InputStream inputStraem = httpResponse.getEntity().getContent();

            StringWriter writer = new StringWriter();
            IOUtils.copy(inputStraem, writer, "UTF-8");
            String output = writer.toString();

            System.out.println(output);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        POCWithoutDevkitTest withoutDevkitClient = new POCWithoutDevkitTest();
        withoutDevkitClient.executeGetRequest("https://appcenter.intuit.com/api/v1/connection/reconnect");
    }

}

Dependencies

依赖关系

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.3.1</version>
    </dependency>
    <dependency>
        <groupId>oauth.signpost</groupId>
        <artifactId>signpost-core</artifactId>
        <version>1.2.1.1</version>
    </dependency>
    <dependency>
        <groupId>oauth.signpost</groupId>
        <artifactId>signpost-commonshttp4</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.3.1</version>
    </dependency>

Thanks

谢谢

回答by Haseb Ansari

This is the working HTTP GET requestcode in java when all keys are in hand. Hope it does your work.

当所有密钥都在手时,这是在 java 中工作的 HTTP GET 请求代码。希望它能完成你的工作。

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.*;  //HttpHead, HttpPut, HttpGet, etc...
import org.apache.http.util.EntityUtils;

public class HttpGetRequest {

public static void demo() throws IOException {           
    String consumer_key = "bcd";
    String consumer_secret = "efg";
    String access_token = "rst";
    String access_secret= "xzy";

    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumer_key,
consumer_secret);
    consumer.setTokenWithSecret(access_token, access_secret);


    String uri = "your url here";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(uri);
    try {
        consumer.sign(httpget);
    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE,       null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpResponse response = httpclient.execute(httpget);
    System.out.println(response.getStatusLine().toString());
    HttpEntity entity = response.getEntity();
    System.out.println();
    System.out.println(EntityUtils.toString(entity));       
}
public static void main(String[] args) {
    try {
        demo();
    }
    catch(IOException ioe) {
        System.out.println(ioe);
    }
}
}

回答by robotdan

Here is a builder I created to build the OAuth v1 Authorization header. You may find it useful.

这是我为构建 OAuth v1 授权标头而创建的构建器。你可能会发现它很有用。

https://gist.github.com/robotdan/33f5834399b6b30fea2ae59e87823e1d

https://gist.github.com/robotdan/33f5834399b6b30fea2ae59e87823e1d

Example usage calling Twitter:

调用 Twitter 的示例用法:

String authorizationHeader = new OAuth1AuthorizationHeaderBuilder()
         .withMethod("POST")
         .withURL("https://api.twitter.com/oauth/access_token")
         .withConsumerSecret("twitterConsumerSecret")
         .withTokenSecret("your_oauth_token_secret")
         .withParameter("oauth_consumer_key", "your_consumer_key")
         .withParameter("oauth_token", "your_oauth_token")
         .build()