【问题标题】:How to call REST API which supports RQL (Resource Query Language) using Java如何使用 Java 调用支持 RQL(资源查询语言)的 REST API
【发布时间】:2021-02-09 07:26:39
【问题描述】:

我正在尝试使用 Java 使用 REST API。使用 Oauth1 进行身份验证。代码块如下-

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 javax.swing.text.html.FormSubmitEvent;

public class Oauth1RestCallWithOutToken {
    private OAuthConsumer oAuthConsumer;

    public Oauth1RestCallWithOutToken() {
        String consumerKey = "my_consumer_key";
        String consumerSecret = "my_consumer_secret";
        setupContext(consumerKey, consumerSecret);
    }

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

    public void authorize(HttpRequestBase httpRequest)  {
        try {
            oAuthConsumer.sign(httpRequest);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException 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(FormSubmitEvent.MethodType.GET.toString())) {
            httpRequest = new HttpGet(uri);
        }

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

        try {
            authorize(httpRequest);
        } catch (Exception 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[]) {
        String url="https:host/order-manager/orders";
        //url="https:host/order-manager/orders?in(internalId,12345)";
        Oauth1RestCallWithOutToken withoutDevkitClient = new Oauth1RestCallWithOutToken();
        withoutDevkitClient.executeGetRequest(url);
    }

}

依赖关系-

<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>
    </dependencies>

如果使用诸如“https:host/order-manager/orders”之类的 URL,我将获得成功的响应。 但是,如果使用包含 RQL 参数的 URL,例如“https:host/order-manager/orders?in(internalId,12345)”,我会收到 500 个响应。在使用 Postman 或 Insomnia 时,这两个 URL 都可以正常工作。
你能帮我指出我的错误吗?或使用 java 使用 RQL 支持的 REST API 的任何建议。提前致谢。

【问题讨论】:

    标签: java api rest


    【解决方案1】:

    终于解决了。代码如下-

    import java.io.InputStream;
    import java.io.StringWriter;
    import java.net.URI;
    import java.net.URISyntaxException;
    import com.google.api.client.auth.oauth.OAuthHmacSigner;
    import com.google.api.client.auth.oauth.OAuthParameters;
    import com.google.api.client.http.GenericUrl;
    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 javax.swing.text.html.FormSubmitEvent;
    
    public class Oauth1RQLRestCallWithOutToken {
        private final String consumerKey = "consumerKey";
        private final String consumerSecret = "consumerSecret";
    
        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(FormSubmitEvent.MethodType.GET.toString())) {
                httpRequest = new HttpGet(uri);
            }
    
            httpRequest.addHeader("content-type", "application/json");
            httpRequest.addHeader("Accept","application/json");
    
            //Generate Authorization header
            try{
                String headerValue=getAuthorizationHeader(customURIString,methodtype);
                httpRequest.setHeader("Authorization",headerValue);
            }catch (Exception ex){
                System.out.println("Error: "+ex.getMessage());
            }
    
    
            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();
            }
        }
    
        private  String getAuthorizationHeader(String url, String method) throws Exception {
            OAuthParameters oauthParams = new OAuthParameters();
            oauthParams.version = "1.0";
            oauthParams.consumerKey = consumerKey;
            oauthParams.computeNonce();
            oauthParams.computeTimestamp();
    
            OAuthHmacSigner oauthSigner = new OAuthHmacSigner();
            oauthSigner.clientSharedSecret = consumerSecret;
    
            oauthParams.signer = oauthSigner;
            oauthParams.computeSignature(method,
                    new GenericUrl(url)
            );
    
            return oauthParams.getAuthorizationHeader();
        }
    
        public static void main(String args[]) {
            String url="https:host/order-manager/orders";
            url="https:hosts/order-manager/orders?in(internalId,12345)";
            Oauth1RQLRestCallWithOutToken rqlRestCallWithOutToken = new Oauth1RQLRestCallWithOutToken();
            rqlRestCallWithOutToken.executeGetRequest(url);
        }    
    }
    

    依赖关系-

    <dependencies>
        <dependency>
                <groupId>com.google.http-client</groupId>
                <artifactId>google-http-client</artifactId>
                <version>1.38.1</version>
        </dependency>
        <dependency>
                <groupId>com.google.oauth-client</groupId>
                <artifactId>google-oauth-client</artifactId>
                <version>1.31.4</version>
        </dependency>
        <dependency>
                <groupId>com.intuit.quickbooks-online</groupId>
                <artifactId>ipp-v3-java-devkit</artifactId>
                <classifier>jar-with-dependencies</classifier>
                <version> 6.0.7 </version>
         </dependency>
    </dependencies>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多