0

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";
}

}

  • Does this answer your question? [Using HttpURLConnection to POST in Java](https://stackoverflow.com/questions/26940410/using-httpurlconnection-to-post-in-java) – Queeg Jul 05 '22 at 20:40
  • Unfortunately not, the API is still returning the login screen – Jordan Reighn Jul 06 '22 at 05:57
  • This is why I believe the auth is not correct, – Jordan Reighn Jul 06 '22 at 06:06
  • It is not clear to me what you need. Can you run the POST request? Can you authenticate? Or is the issue to parse JSON? – Queeg Jul 06 '22 at 06:21
  • As I mentioned my issue seems to be authentication. It seems to me when I set the authentication property to basic, it is wrong, however in Postman that's exactly how I have it. A post request with basic auth. The API code I have there in the java is functional as it returns a failed auth request – Jordan Reighn Jul 06 '22 at 07:03

0 Answers0