首页 > 解决方案 > Ameritrade API POST 请求 JSON 响应

问题描述

我已经很多年没有用 JAVA 编码了,并且正在尝试将一种算法放在一起,以根据某些条件自动进行交易。

我希望使用 Ameritrade API

我已经尝试在命令提示符下发送一条 cURL 消息,并且确实从服务器“无效密钥”得到响应。我希望看到“无效密钥”响应在 Java 中返回,因为这将证明我可以将 POST 和接收 JSON 对象发送回 Java。从那里开始,我将一步一步地进行身份验证!

这是在命令提示符下发送的 curl 消息,可以通过复制和粘贴自己尝试:

curl -X POST -H "内容类型:应用程序/x-www-form-urlencoded" -d "grant_type=authorization_code&refresh_token=&access_type=offline&code=&client_id=&redirect_uri="" https://api.tdameritrade.com/v1/ oauth2/令牌

我想做的第一件事是能够在 JAVA 中发送此 curl 消息并在 JAVA 中接收 JSON 响应

到目前为止,这就是我所拥有的代码,但是我收到一个 500 错误,这让我认为它与我将消息发送到服务器的方式有关?

public void trytoAuthenticate() {
    HttpURLConnection connection = null;
    //
    //this is the curl message in command prompt you can send to receive JSON response back
    //curl -X POST --header "Content-Type: application/x-www-form-urlencoded" -d 
    //"grant_type=authorization_code&
    //refresh_token=&
    //access_type=offline&
    //code=&
    //client_id=&
    //redirect_uri=" "https://api.tdameritrade.com/v1/oauth2/token"

    try {
        //Create connection
        URL url = new URL("https://api.tdameritrade.com/v1/oauth2/token");
        String urlParameters = "grant_type=" + URLEncoder.encode("authorization_code", "UTF-8") + 
                "&refresh_token=" + URLEncoder.encode("", "UTF-8") + 
                "&access_type=" + URLEncoder.encode("", "UTF-8") + 
                "&code=" + URLEncoder.encode("", "UTF-8") + 
                "&client_id=" + URLEncoder.encode("", "UTF-8") + 
                "&redirect_uri=" + URLEncoder.encode("", "UTF-8");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //-X
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //-H
        connection.setRequestProperty("Content-Length", 
                Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");  

        connection.setUseCaches(false);
        connection.setDoOutput(true);//connection will be output
        connection.setDoInput(true);//connection will be input

        //Send request
        DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
        wr.writeBytes(urlParameters);
        System.out.println(urlParameters); //added for testing
        wr.close();

        //Get Response  
        DataInputStream is = new DataInputStream (connection.getInputStream());
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        rd.readLine();
        //StringBuffer response = new StringBuffer(); // or StringBuffer/StringBuilder if Java version 5+
        //String line;
        //while ((line = rd.readLine()) != null) {
        //  response.append(line);
        //  response.append('\r');
        //}
        rd.close();
        //System.out.println(response.toString());
        //return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        //return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
}

标签: javajsoncurl

解决方案


一些东西:

您需要四个参数:grant_type、access_type、redirect_url 和 code。

  1. 您应该 URLDecode 从您可能刚刚执行的浏览器登录中获得的授权代码(按照他们的说明)

  2. 去掉空参数,只留下我上面提到的。

  3. 重定向 URL 必须与您在控制台中创建 APP 时添加的重定向 URL 完全匹配。

  4. 如果这是一个应用程序(看起来像),您可能必须将 access_type 设置为“离线”。再次查看他们的文档。取决于您的应用程序。

  5. grant_type 应该是“authorization_code”,因为这就是你想要的。


推荐阅读