Http authorization
I det nedenstående er der beskrevet hvad jeg gør for at tilgå en webserver, som har basic authorization integreret. Dvs, at jeg skal specificere brugernavn og password i en header.Ligemeget hvad jeg gør, så får jeg responsekode 401 = UnAuthorized. Ufattelig taknemmlig, hvis i kan løse den her!
public byte[] recieveFile(String fileName, String filePath) throws Exception {
try {
if((!fileName.equalsIgnoreCase(".")) && (!fileName.equalsIgnoreCase(".."))) {
URL url = new URL("http://pc187/");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.connect();
String name = con.getHeaderField("WWW-Authenticate");
//If we get response for Authenticate, then the webserver is protected by username and passwword.
if(name != null) {
System.out.println(name);
String temp = new String(USERNAME+":"+PASSWORD);
BASE64Encoder encoder = new BASE64Encoder();
temp = encoder.encode(temp.getBytes());
System.out.println("after encode: "+temp);
con.disconnect();
con.setRequestProperty("Authorization","Basic "+temp);
con.connect();
}
//We are now connected to the webserver, and ready for download.
if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("ok");
/*
if(socket.isBound()){
InputStream is = socket.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] bytes = new byte[BYTES_TO_READ];
int i = is.read(bytes);
while(i >= 0) {
os.write(bytes, 0, i);
i = is.read(bytes);
}
os.close();
is.close();
socket.close();
*/
con.disconnect();
return new byte[0];
}
else{
System.out.println("FEJL: code: "+con.getResponseCode());
con.disconnect();
return new byte[0];
