I'm trying to add header for my request using HttpUrlConnection
but the method setRequestProperty()
doesn't seem working. The server side doesn't receive any request with my header.
HttpURLConnection hc;
try {
String authorization = "";
URL address = new URL(url);
hc = (HttpURLConnection) address.openConnection();
hc.setDoOutput(true);
hc.setDoInput(true);
hc.setUseCaches(false);
if (username != null && password != null) {
authorization = username + ":" + password;
}
if (authorization != null) {
byte[] encodedBytes;
encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + encodedBytes;
hc.setRequestProperty("Authorization", authorization);
}
Finally this worked for me
Your code is fine.You can also use the same thing in this way.
Its Return response code 200 if authorizationis success
Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the
encodedBytes
variable is abyte[]
and not aString
value. If you pass thebyte[]
to anew String()
as below, the code snippet works perfectly.If you are using Java 8, use the code below.
I have used the following code in the past and it had worked with basic authentication enabled in TomCat:
You can try the above code. The code above is for POST, and you can modify it for GET
With RestAssurd you can also do the following: