I was facing this issue, as mentioned in title, when I tried to make request to another https spotify api endpoint to request for access token on-demand (right now, I have it hard-coded in my environment file). My spring-boot app runs over plain http protocol, and I am guessing that since my spring-boot app doesn't enable https, it won't present any valid SSL certificate to the spotify API endpoint for my request to actually get approved and reach the endpoint. However, I also don't want to go through the entire painful process of setting up my spring-boot app with https enabled as that would mean getting my own custom domain, getting valid certificate from root CA, and setting it up for my java springboot project just so I can call upon https endpoints. Much suggestions would be appreciated how to resolve this issue.
Here is my FormController.java file:
package com.example.play_app_backend.controllers;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.play_app_backend.FormData;
import org.springframework.web.bind.annotation.RequestBody;
import com.example.play_app_backend.SpotifyApiClient;
@RestController
@RequestMapping("/api")
public class FormController {
private SpotifyApiClient spotifyClient;
public FormController() {
spotifyClient = new SpotifyApiClient();
}
// helper to construct the query parameter q's query string!
public String constructQueryString(FormData d) {
String query = String.format("artist:%s genre:%s",
d.getArtist(),
d.getGenre());
System.out.printf("Query String: %s", query);
return query;
}
@PostMapping
public String handleFormSubmission(@RequestBody FormData data) {
try {
//String accessToken = spotifyClient.getAccessToken();
String accessToken = spotifyClient.getAccessToken();
System.out.println("accessToken: " + accessToken);
// now, with accessToken, we should utilize the data gotten from front-end to
// look for Spotify tracks
// that best match user criteria!
// base url of api endpoint for /search!
String apiUrl = "https://api.spotify.com/v1/search";
String queryString = constructQueryString(data);
// full url containing necessary query params!
String fullUrl = apiUrl + '?' + "q=" + queryString + " &type=track";
System.out.println("full Url: " + fullUrl);
OkHttpClient httpClient = new OkHttpClient();
Request req = new Request.Builder().url(fullUrl).addHeader("Authorization", "Bearer " + accessToken).get()
.build();
try (Response resp = httpClient.newCall(req).execute()) {
if (resp.isSuccessful()) {
String responseBody = resp.body().string();
return responseBody;
} else {
return "failed to fetch tracks from spotify /search api endpoint!";
}
} catch (Exception e) {
return "Error: " + e.getMessage();
}
} catch (Exception e) {
String errorMsg = "can't get access token" + e.getMessage();
return errorMsg;
}
}
}