javaodataolingo

how to authenticate on an odata2 service in java? (Basic Auth)


I'm trying to make a request with java on this OData2 API => https://scihub.copernicus.eu/dhus/odata/v1/ for a project. But I can't without authentication. I have personal logs, as a user I don't have any problems. When I tried with java it gave an error 401.

I try this:

     String auth = user + ":" + password;
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     String basicAuth = "Basic " + new String(new Base64().encode(auth.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.connect();
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);
    System.out.println(url.toString());

But it doesn't works. When i print the responseCode i have a 400 error and i try also another code it was a 401 error.

With PostMan i only need the BasicAuth to have an access and it works. And i'm using Olingo2.

I'm new on java web and i don't have any idea. In the first step i only want to have the authentication. And then doing queries.

Thank you!


Solution

  • For the 401 case there is something wrong with the authorization,otherwise the general approach is right.

    For the 400 case, browsers and tools like postman will automatically send additional headers, which the code will be missing. I reused the about code and passed an additional header Accept : application/xml and was able to retrieve the response. Below is the working code. Cheers!

    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    
    public class Test1 {
    
        public static void main(String[] args) throws IOException {
            String user = "ENTER YOUR USERNAME";
            String password = "ENTER YOUR PASSWORD";
            String auth = user + ":" + password;
            URL url = new URL("https://scihub.copernicus.eu/dhus/odata/v1/");
    
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/xml");
            String basicAuth = "Basic " + Base64.getEncoder().encodeToString((auth).getBytes(StandardCharsets.UTF_8)); // Java
            connection.setRequestProperty("Authorization", basicAuth);
            connection.connect();
            System.out.println(connection.getResponseCode());
            System.out.println(connection.getContent());
    
        }
    
    }