'Calling an API that have username and password in Java

I'm trying to connect to an API that has a username and password with this code:

try {
    URL url = new URL("https://url?UserName=username&Password=password");
    Connection = (HttpURLConnection) url.openConnection();

    //Request setup
    Connection.setRequestMethod("GET");
    Connection.setConnectTimeout(5000);
    Connection.setReadTimeout(5000);
    int status = Connection.getResponseCode();
    System.out.println(status);

}
catch (MalformedURLException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}

But I get the error:

java.net.SocketException: Connection reset

I kept searching and I found another format for the URL which is:

URL url = new URL("Https:username:password@url);

When I tried, it gave me the error:

java.net.MalformedURLException: For input string:password@url

I tried to separate the URL into three strings and made the password Integer.pharsInt("String"), but it also didn't work. The password has words, numbers, and a special character!

What am I doing wrong?



Solution 1:[1]

Try to encode your URL, this way:

HttpURLConnection connection = (HttpURLConnection)
    new URL("https://url?UserName" +
            URLEncoder.encode(username, "UTF-8") +
            "&Password=" +
            URLEncoder.encode(password, "UTF-8"))
            .openConnection();

connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
InputStream is = connection.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

// The rest of your code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen