1

I need to connect to an API through https but it needs authorisation.
I have the login name and password for it, but have no idea how to transfer it to https.

The code I tried to use the following code (which got from another SO post):

public class TestHTTPSRequest {
public static void main(String[] args) throws Exception {
    URLConnection connection = new URL("https://smartcat.ai/api/integration/v1/account").openConnection();

    InputStream is = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(is);
    char[] buffer = new char[256];
    int rc;

    StringBuilder sb = new StringBuilder();

    while ((rc = reader.read(buffer)) != -1)
        sb.append(buffer, 0, rc);

    reader.close();

    System.out.println(sb);
}
}
Rick van Lieshout
  • 2,276
  • 2
  • 22
  • 39
  • 1
    [this](http://stackoverflow.com/questions/3283234/http-basic-authentication-in-java-using-httpclient) may help you. – jack jay Jan 18 '17 at 11:57
  • Read the documentation for the API you are trying to use. That should explain how to supply the authorization information. (There is no solution that is going to work for all APIs ...) – Stephen C Jan 18 '17 at 11:59
  • Tanks a lot. Requesting their technical support for docs. You helped a lot as i thought that should be something universal. – Victor Kuryshev Jan 18 '17 at 12:20

2 Answers2

0

Please try to use HTTPClient. You can easily connect to the https urls.

Also if it is a secured url You would need some security headers They can be

1> Authentication-token or any other token

2> You can need some other tokens for the sake of CSRF protection

Please explore the documentation of the API

Saket Puranik
  • 115
  • 2
  • 8
0

Jack Jay's link helped. The following method work for me well:

public static void main(String[] args) {

    try {
        URL url = new URL ("https://.../......");
        String encoding = Base64.getEncoder().encodeToString(("login:password").getBytes());

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty  ("Authorization", "Basic " + encoding);
        InputStream content = (InputStream)connection.getInputStream();
        BufferedReader in   =
                new BufferedReader (new InputStreamReader (content));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }

}