Я не кодировал в JAVA в течение многих лет и пытаюсь собрать алгоритм для автоматического совершения сделок на основе определенных условий.
Я надеюсь использовать API Ameritrade
Я попытался отправить сообщение cURL в командной строке, и я действительно получил ответ от сервера «Неверный ключ».Мне бы хотелось, чтобы ответ «Неверный ключ» возвращался в Java, поскольку это докажет, что я могу отправлять POST и получать объекты JSON обратно в Java.Оттуда я буду работать над аутентификацией, но по одному шагу за раз!
Вот сообщение curl, отправленное в командной строке, которое работает, попробуйте сами, скопировав и вставив: *
curl -X POST -H "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
Первое, что я хотел бы сделать, - это иметь возможность отправить это сообщение скручивания в JAVA и получитьответ JSON назад в JAVA
Это то, что у меня есть для кода до сих пор, но я получаю ошибку 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();
}
}
}
}