BAD REQUEST error while trying to get accesstoken through JAVA

rajeshreddyrr@gmail.com
Hi,

I have below code for getting access token. I am getting response status as 400 and response message as "BAD REQUEST".
public String getSessionKey(){
BufferedReader rd = null;
StringBuilder sb = null;
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL("https://api.kite.trade/session/token");

String checksum = getSHA256Hash(api_key+request_token+secret_key);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setRequestProperty("api_key", api_key);
conn.setRequestProperty("request_token", request_token);
conn.setRequestProperty("checksum", checksum);

conn.connect();

int status = conn.getResponseCode();
System.out.println(conn.getResponseMessage());
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return stringBuilder.toString();
}
/**
* Returns a hexadecimal encoded SHA-256 hash for the input String.
* @param data
* @return
*/
private String getSHA256Hash(String data) {
String result = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data.getBytes("UTF-8"));
return DatatypeConverter.printHexBinary(hash); // make it printable
}catch(Exception ex) {
ex.printStackTrace();
}
return result;
}


Am i missing something here.
  • Kailash
    Logically, this looks correct. Any API related error should come back with a JSON response (including an error message). If you're not getting a JSON response, the POST request you making may be problematic in itself.
  • RH1558
    rajeshreddyrr@gmail.com your response status as 400 and response message as "BAD REQUEST" problem solve?
  • rajeshreddyrr@gmail.com
    Hi RH, I didn't get time to look into it. If you are successfull in getting session token and placing orders, can you post me the code.

    Rajesh
  • rajeshreddyrr@gmail.com
    Hi RH1558, Isue is resolved by directly creating URL string instead of setting request properties.
    Ex:
    URL url = new URL("https://api.kite.trade/session/token?api_key=&request_token="+request_token+"&checksum="+sha256hex);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.connect();

    int status = conn.getResponseCode();
This discussion has been closed.