Sending an HTTPS request from a Java application

Question:

What are the ways to send https requests from a desktop java application? Of particular interest is the source code example.

Answer:

The most primitive way is to use URLConnection . Here is an example without error handling, encodings and other husks:

public static void main(String[] args) throws Exception {
    URLConnection connection = new URL("https://www.dev.java.net/servlets/ProjectList").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);
}

In case it turns out that the standard URLConnection (more precisely, in fact, HttpsUrlConnection is created) cannot do something, then use the Apache HTTP Client .

Scroll to Top