我已经很多年没有用JAVA编写代码了,我正在试着把一种算法组合在一起,以便根据特定的条件自动进行交易。
我希望使用Ameritrade API。
我尝试过在命令提示符下发送cURL消息,但确实收到了来自服务器“无效密钥”的响应。我希望看到在Java中返回“无效的键”响应,因为这将证明我可以向Java发送POST和接收JSON对象。从那里开始,我将进行身份验证,但要一步一步来!
这是在命令提示符中发送的curl消息,可以通过复制和粘贴来亲自尝试::
"grant_type=authorization_code&refresh_token=&access_type=offline&code=&client_id=&redirect_uri=“-X POST -H”内容类型:应用程序/x-www-form-urlencoded“-d curl”https://api.tdameritrade.com/v1/oauth2/token
我想做的第一件事是能够用JAVA发送这个curl消息,并用JAVA接收返回的JSON响应
这就是我到目前为止的代码,但我得到了一个500错误,这让我认为是im发送消息到服务器的方式有问题?
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();
}
}
}
}发布于 2020-09-24 01:32:52
以下是一些事情:
您需要四个参数: grant_type、access_type、redirect_url和代码。
https://stackoverflow.com/questions/53907821
复制相似问题