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);
}
connect()
on the URLConnection?connection.setRequestMethod("GET");
(or POST or whatever you want)?authorization
to the empty string. If eitherusername
orpassword
is null, thenauthorization
will be the empty string, not null. Therefore, the finalif
will get executed, but the"Authorization"
property will be set to empty, seems to me.