Copia de arquivo com autenticação

0 respostas
C

Preciso copiar um arquivo de um servidor para outro, e para acessar o servidor que possui o arquivo preciso fazer autenticação. Peguei os 3 exemplos na internet, mas nenhum deles funciona. Alguém saberia me dizer o porque e como que faço para funcionar?

Exemplo 1

public class CopyFile {
	public static void main(String[] args) {
	    System.out.println("sss");
		try {
	        // Create channel on the source
	        FileChannel srcChannel = new FileInputStream("C:\\aaa.txt").getChannel();
	    
	        // Create channel on the destination
	        FileChannel dstChannel = new FileOutputStream("\\\\10.2.1.201\\publico\\temp\\bbb.txt").getChannel();
	    
	        // Copy file contents from source to destination
	        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
	    
	        // Close the channels
	        srcChannel.close();
	        dstChannel.close();
	    } catch (Exception e) {
	    	System.out.println(e);
	    }
	}
}

Exemplo 2

public class CopyFile {
	public static void main(String[] args) throws Exception {
		URL url = new URL("file:////10.2.1.201/publico/temp/bbb.txt");
		URLConnection urlc = url.openConnection();
		String encoding = new sun.misc.BASE64Encoder().encode("user1:pass1".getBytes());
		urlc.setRequestProperty ("Authorization", "Basic " + encoding);
		BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) urlc.getInputStream()));
		String s = in.readLine();
		System.out.println(s);
	}
}

Exemplo 3

public class CopyFile extends Authenticator {
	public CopyFile() {
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication("user1", "pass1".toCharArray());
	}

	public static void main(String[] args) throws Exception {
		CopyFile obj = new CopyFile();
		Authenticator.setDefault(obj);
		URL url = new URL("file:////10.2.1.201/publico/temp/bbb.txt");
		URLConnection urlc = url.openConnection();
		urlc.setDefaultAllowUserInteraction(true);
		BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) urlc.getInputStream()));
		String s = in.readLine();
		System.out.println(s);
	}
}

Nos 3 exemplos a seguinte exceção é lançada:

Exception in thread main java.io.FileNotFoundException: \10.2.1.201\publico\temp\bbb.txt (Logon failure: unknown user name or bad password)

at java.io.FileInputStream.open(Native Method)

at java.io.FileInputStream.<init>(Unknown Source)

at java.io.FileInputStream.<init>(Unknown Source)

at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)

at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)

at file.CopyFile.main(CopyFile.java:57)

Valeu

Criado 30 de julho de 2007
Respostas 0
Participantes 1