I am using the following code to send a REST request, the request is failed (401 error) because it needs username and password.
how to add them to the url ? even when I copy the url in browser and add the username and password to the end of it the browser pop out the login page, so I suppose in the code I should add the username and password parameters but how ?
URL url = new URL("www.example.com/user?ID=1234");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
I added the following to the code but still run into 401 error.
conn.setRequestProperty("username", "myusername");
conn.setRequestProperty("password", "mypassword");