I am new to Rest API based on Java. The purpose is to obtain an access token from a particular API Token URL by sending a POST request. However, upon running the following program, the access token cannot be used (invalid token) after executing the Post and Get requests.
I would like to know if there is anything I would need to improve. Note that the requirements to retrieve the JSON data include the following info such as the url, the client_id and the grant_type.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toMap;
public class Main {
public static void main(String[] args) throws IOException {
useBearerToken(getAUthToken());
}
private static String getAUthToken() throws IOException {
String URL = "http://api/service/get_token";
URL obj = new URL(URL);
String auth = "something";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", authHeaderValue);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
final String POST_PARAMS = "grant_type=client_credentials&client_id=something";
// Start: For POST only
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// End: For POST only
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
return get_token(response);
} else {
throw new IOException("POST request does not worked");
}
}
private static String get_token(StringBuffer response) {
String res1 = response.toString();
String retrieved_token = null;
Map<String, String> skipDuplicatesMap = Stream.of(res1.split(",")).
map(el -> el.split(":")).
collect(toMap(arr -> arr[0], arr -> arr[1], (oldValue, newValue) -> oldValue));
for(String key : skipDuplicatesMap.keySet()) {
if (key.contains("access_token")) {
retrieved_token = skipDuplicatesMap.get(key);
}
}
String the_token = retrieved_token.substring(1,retrieved_token.length() - 1);
return the_token;
}
private static void useBearerToken(String access_token) throws IOException {
// Sending get request
URL url = new URL("http://api/service/get_records?source=etp&startEntryDate=2022-01-07&endEntryDate=2022-01-22");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
StringBuffer response = null;
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
String authString = "Bearer " + access_token;
con.setRequestProperty("Authorization", authString);
//System.out.println(authString);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} else {
System.out.println("GET request does not worked");
}
}
}
Thank you so much. If there is anything I am missing, I would be highly appreciated.