I am extremely new to coding in Java and recently decided to take up a project on it. I am writing an API Class, that calls an external API method to return data. However I am just not coming right, I have tried just about every other stackoverflow link for this.
My problem seems to be that my authentication is not correct as when I call the API which I have just written, I get returned to the login screen. This only ever happens when I have the Authentication incorrect in postman.
On a side note, I usually write up my API calls in Postman and copy and paste the code over, this does not seem to be the trick with this project? My API returns JSON code, is there a way for me to serialize this into an object and return the json, as in my opinion a normal API should?
@Path("SomePath")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({MediaType.APPLICATION_JSON})
public class SomeApi extends BaseResource {
@PermitAll
@GET
public String get() throws IOException
{
try {
URL url = new URL("https://top-secret.com/home/tricks");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization",
"Basic" + Base64.getEncoder().encodeToString(
("Username" + ":" + "Password").getBytes()
));
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
return "Yay";
}
}