Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

ftpwebrequest - Howto do a simple ftp get file on Android

I can't find an example of a simple FTP access of a file anywhere, and the FTPClient class (which a couple of examples use) doesn't appear in the Android Class Index. I've got http access working, but how do I do a simple FTP get? All I want to do is download (for example): ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/KABQ.TXT It shouldn't require login, change directory, etc. Just giving that URL to the http access methods don't seem to work.

This is similar to the question at: unable to read file from ftp in android?

I tried a simple:

  StringBuilder response = new StringBuilder();
  URLConnection ftpConn;
  try {
  URL netUrl = new URL("ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/KABQ.TXT");
  ftpConn = netUrl.openConnection();
  BufferedInputStream bufRd = new BufferedInputStream(ftpConn.getInputStream());
  int temp;
  while ((temp = bufRd.read()) != -1) {
      response.append(temp);
  }
  bufRd.close();
  } catch (Exception e) {
      return "Failure";
  }

but it gets an exception on getInputStream: Unable to connect to server: Unable to configure data port

Also, there must be a more intelligent way to pull the data out of the stream buffer than byte-by-byte, isn't there? I can't find that either.

Lastly, I need to do both http and ftp access, is there any reason not to use URLConnection for both access types? or is it better to use HttpConnection for http and URLConnection for ftp?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Whew! I finally got it going. I gave up on the simple way that works in webOS and WPF/C# where you can just do a ftp:://... you have to use the FTPClient package.

After fixing the library access (Project | Properties | Java Build Path | Libraries | Add JARs...) I fiddled with the calls until it started working. Here's the sequence of my FTPClient calls. It wouldn't work until I set it in passive mode.

  mFTPClient = new FTPClient();
  mFTPClient.connect("tgftp.nws.noaa.gov");      
  mFTPClient.login("anonymous","nobody");
  mFTPClient.enterLocalPassiveMode();
  mFTPClient.changeWorkingDirectory("/data/forecasts/taf/stations");
  InputStream inStream = mFTPClient.retrieveFileStream("KABQ.TXT");
  InputStreamReader isr = new InputStreamReader(inStream, "UTF8");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...