Do swojego managera pobierania przez protokół HTTP (działa) postanowiłem dodać obsługę FTP. Póki co z marnym skutkiem, bo to już nie działa. Poniżej dwie metody odpowiedzialne za nawiązanie połączenia i pobranie pliku. Gdyby ktoś miał jakieś konstruktywne uwagi, będę wdzięczny.
public synchronized InputStream connectFtp(String host) throws IOException{
socket = new Socket(host, 21);
InputStream inStream = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(inStream));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String response;
writer.write("USER " + "anonymous\r\n");
writer.flush();
response = reader.readLine();
if (!response.startsWith("331 ")){
throw new IOException();
}
writer.write("PASS " + "anonymous\r\n");
writer.flush();
response = reader.readLine();
if (!response.startsWith("230 ")){
throw new IOException();
}
return inStream;
}
public void run(){
RandomAccessFile file = null;
InputStream stream = null;
try{
if(isFtp) { //jezeli to protokol ftp
stream = connectFtp(url.toString());
int contentLength = stream.available();
if (contentLength < 1) error();
if (size == -1){
size = contentLength;
stateChanged();
}
} else { //jezeli to protokol http
(...)
}
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
while(status == DOWNLOADING){
byte buffer[];
if (size - downloaded > 1024){
buffer = new byte[1024];
}else{
buffer = new byte[size - downloaded];
}
int read = stream.read(buffer);
if(read == -1)
break;
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
if (status == DOWNLOADING){
status = COMPLETE;
stateChanged();
}
}catch(Exception e){
error();
}finally{
try {
if(isFtp){
//disconnect();
writer.write("QUIT " + "anonymous\r\n");
writer.close();
reader.close();
socket = null;
}
if (file != null){
file.close();
}
if(stream != null){
stream.close();
}
} catch (Exception e) {}
}
}