package com.xwtec.interfaceplatform.commons.util;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HttpClientUtils {
private static final Log logger = LogFactory.getLog(HttpClientUtils.class);
private static HttpClient client;
static {
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
client = new HttpClient(connectionManager);
client.getParams().setConnectionManagerTimeout(3000);
}
public static String doGet(String url, String charset) throws Exception {
logger.debug(">>> URL : " + url);
if(url == null || "".equals(url.trim())){
logger.error(">>> an error url : url null!");
return null;
}
GetMethod method = null;
String result = null;
try {
client = new HttpClient();
method = new GetMethod(url);
client.executeMethod(method);
int status = method.getStatusCode();
if(status == HttpStatus.SC_OK){
result = charset == null ? method.getResponseBodyAsString() : new String(method.getResponseBody(), charset);
}else{
logger.error(">>> an error httpstatus returned, status code : " + status);
}
} catch (HttpException e) {
logger.error(e, e);
e.printStackTrace();
throw e;
} catch (IOException e) {
logger.error(e, e);
e.printStackTrace();
throw e;
} finally {
// 释放连接
if(method != null){
method.releaseConnection();
}
}
return result;
}
public static String doPost(String url, Map<String,String> params, String charset) throws Exception {
logger.debug(">>> URL : " + url);
if(url == null || "".equals(url.trim())){
logger.error(">>> an error url : url null!");
return null;
}
PostMethod method = null;
String result = null;
try {
client = new HttpClient();
method = new PostMethod(url);
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
if(params != null && !params.isEmpty()){
String key = null;
for(Map.Entry<String, String> entry : params.entrySet()){
key = entry.getKey();
if(key != null && !"".equals(key.trim())){
//method.setParameter(key, new String(entry.getValue().getBytes(), "UTF-8"));
method.setParameter(key, entry.getValue());
}
}
}
client.executeMethod(method);
int status = method.getStatusCode();
if(status == HttpStatus.SC_OK){
result = charset == null ? method.getResponseBodyAsString() : new String(method.getResponseBody(), charset);
}else{
logger.error(">>> a error httpstatus returned, status code : " + status);
}
} catch (HttpException e) {
logger.error(e, e);
e.printStackTrace();
throw e;
} catch (IOException e) {
logger.error(e, e);
e.printStackTrace();
throw e;
} finally {
// 释放连接
if(method != null){
method.releaseConnection();
}
}
return result;
}
}
package com.xwtech.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
/**
*
* @Title: FTPUtil.java
* @Description:FTP工具类
*/
public class FTPUtil
{
// private final static Logger log = Logger.getLogger(FTPUtil.class);
public FTPClient ftpClient;
/**
* 是否用二进制方式传输
*/
private boolean binaryTransfer = false;
private String server;//服务器
private int port; //端口
private String username;//ftp用户名
private String password;//ftp用户密码
private int connecttimeout=3000;
private int datatimeout=3000;
public List fileListDetail = new ArrayList();
public List fileListDir = new ArrayList();
public int getConnecttimeout() {
return connecttimeout;
}
public void setConnecttimeout(int connecttimeout) {
this.connecttimeout = connecttimeout;
}
public int getDatatimeout() {
return datatimeout;
}
public void setDatatimeout(int datatimeout) {
this.datatimeout = datatimeout;
}
/**
* @param server
* ftp服务器地址
* @param port
* ftp端口
* @param user
* ftp服务器登陆用户
* @param password
* ftp用户密码
*/
public FTPUtil(String server, int port, String username, String password)
{
System.out.println("FTPUtil start ...");
try{
this.server = server;
this.port = port;
this.username = username;
this.password = password;
this.connecttimeout=3000;
this.datatimeout=3000;
//if(ftpClient==null)
System.out.println("...sos ...");
ftpClient = new FTPClient();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("FTPUtil end ...");
}
/**
* 直接连接FTP
*
* @throws SocketException
* @throws IOException
*/
public boolean connect() throws SocketException, Exception
{
boolean ilogin=ftpClient.isConnected();
int icount=0;
//System.out.println("~~~~~~~~ilogin="+ilogin);
while(!ilogin && icount<3)
{
try{
ilogin=connect("");
}catch (Exception e)
{
e.printStackTrace();
}
icount++;
}
// connect("");
return ilogin;
}
/**
* 连接到FTP指定子目录下
*
* @param path
* @throws SocketException
* @throws IOException
*/
public boolean connect(String path) throws Exception
{
// log.debug("连接FTP Server " + server);
boolean bflag=false;
ftpClient.setConnectTimeout(connecttimeout);
ftpClient.setDataTimeout(datatimeout);
ftpClient.setDefaultTimeout(datatimeout);
ftpClient.connect(server, port);
// 连接后检测返回码来校验连接是否成功
int reply = ftpClient.getReplyCode();
// log.info("连接返回码 " + reply);
if (FTPReply.isPositiveCompletion(reply))
{
if (ftpClient.login(username, password))
{
bflag=true;
// 设置为passive模式
//ftpClient.enterLocalPassiveMode();
}
}
else
{
ftpClient.disconnect();
// log.error("FTP server 拒绝连接");
}
// 连接到子目录下
if (!path.equals(""))
{
ftpClient.changeWorkingDirectory(path);
}
return bflag;
}
/**
* 断开ftp连接
* @throws IOException
*/
public void disconnect() throws Exception
{
try {
ftpClient.logout();
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 改变FTP目录
* @param path
* @return
* @throws IOException
*/
public boolean changeDirectory(String path) throws Exception
{
return ftpClient.changeWorkingDirectory(path);
}
/**
* 创建目录
* @param pathName
* @return
* @throws IOException
*/
public boolean createDirectory(String pathName) throws Exception
{
return ftpClient.makeDirectory(pathName);
}
/**
* 删除目录
* @param path
* @return
* @throws IOException
*/
public boolean removeDirectory(String path) throws Exception
{
return ftpClient.removeDirectory(path);
}
/**
* 删除目录及目录下所有文件
* @param path
* @param isAll
* @return
* @throws IOException
*/
public boolean removeDirectory(String path, boolean isAll) throws Exception
{
if (!isAll)
{
return removeDirectory(path);
}
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr == null || ftpFileArr.length == 0)
{
return removeDirectory(path);
}
//
FTPFile ftpFile=null;
for (int i=0;i<ftpFileArr.length;i++ )
{
ftpFile=ftpFileArr[i];
String name = ftpFile.getName();
if (ftpFile.isDirectory())
{
// log.info("删除子目录 [" + path + "/" + name + "]");
removeDirectory(path + "/" + name, true);
}
else if (ftpFile.isFile())
{
// log.info("删除文件[" + path + "/" + name + "]");
deleteFile(path + "/" + name);
}
else if (ftpFile.isSymbolicLink())
{
}
else if (ftpFile.isUnknown())
{
}
}
return ftpClient.removeDirectory(path);
}
/**
* 检查是否存在指定目录
* @param path
* @return
* @throws IOException
*/
public boolean existDirectory(String path) throws Exception
{
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
FTPFile ftpFile=null;
for (int i=0;i<ftpFileArr.length;i++)
{
if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(path))
{
flag = true;
break;
}
}
return flag;
}
/**
* 检查当前目录下文件是否存在
* @param path
* @return
* @throws IOException
*/
public boolean existFile(String filename) throws Exception
{
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles();
FTPFile ftpFile=null;
for (int i=0;i<ftpFileArr.length;i++)
{
ftpFile=ftpFileArr[i];
if (!ftpFile.isDirectory() && ftpFile.getName().equals(filename))
{
flag = true;
break;
}
}
return flag;
}
/**
* 检查当前目录下文件是否存在
* @param path
* @return
* @throws IOException
*/
public boolean renameFile(String from,String to) throws Exception
{
boolean flag = false;
try{
flag=ftpClient.rename(from, to);
}catch(Exception e)
{
e.printStackTrace();
}
return flag;
}
/**
* 获得当前目录下文件列表
* @return
* @throws IOException
*/
public List getFileList() throws Exception
{
return getFileList("");
}
/**
* 获得指定路径下文件列表
* @param path
* @return
* @throws IOException
*/
public List getFileList(String path) throws Exception
{
FTPFile[] ftpFiles = null;
if (!path.equals(""))
ftpFiles = ftpClient.listFiles(path);
else
ftpFiles = ftpClient.listFiles();
// System.out.println("file size ="+ftpFiles[0].getSize()+" name="+ftpFiles[0].getName()+" ftpFiles="+ftpFiles.length);
List retList = new ArrayList();
if (ftpFiles == null || ftpFiles.length == 0)
{
return retList;
}
FTPFile ftpFile =null;
for (int i=0;i<ftpFiles.length;i++)
{
ftpFile=ftpFiles[i];
if (ftpFile.isFile())
{
retList.add(ftpFile.getName());
}
}
return retList;
}
public void getFileList(String fullpath, boolean isforward)
throws Exception {
FTPFile[] ftpFiles = null;
int icount=0;
boolean iflag=false;
while(icount<3)
{
try{
connect();
ftpFiles = ftpClient.listFiles(fullpath);
iflag=true;
}catch (Exception e)
{
System.out.println("异常了="+fullpath+" 关闭连接重新登陆");
try{
ftpClient.disconnect();
}catch(Exception ex)
{
System.out.println("断开连接异常...");
ex.printStackTrace();
}
e.printStackTrace();
}
if(icount>0)
{
System.out.println("["+icount+"]次登陆标志 iflag="+iflag);
}
if(iflag)
break;
icount++;
}
// System.out.println("路径=" + fullpath + " 文件个数=" + ftpFiles.length);
if (ftpFiles != null && ftpFiles.length > 0) {
FTPFile ftpFile = null;
for (int i = 0; i < ftpFiles.length; i++) {
ftpFile = ftpFiles[i];
// System.out.println("ftpFiles[" + i + "] length="+ ftpFiles.length + " ftpFile=" + ftpFile.getName()+ " isFile=" + ftpFile.isFile());
if (ftpFile.getName()!=null && (!ftpFile.getName().endsWith(".") && !ftpFile.getName().endsWith(".svn"))) {
// System.out.println("ftpFiles[" + i + "] length="+ ftpFiles.length + " ftpFile=" + ftpFile.getName()+ " isFile=" + ftpFile.isFile());
if (ftpFile.isDirectory()) {
getFileList(fullpath + "/" +ftpFile.getName() , true);
Thread.sleep(10); //休息一下
}else //读出的文件名格式转为GBK
{
String filename=new String(ftpFile.getName().getBytes("GBK"), "ISO-8859-1");
String filepath=new String(fullpath.getBytes("GBK"), "ISO-8859-1")+"/"+filename+";"+ftpFile.getSize();
filepath=filepath.replace((char)92,(char)47);
//System.out.println(filepath);
fileListDetail.add(filename);
}
}
}
}
}
public boolean isExistDir(FTPFile[] ftpFiles)
{
boolean iflag=false;
if(ftpFiles!=null)
{
for(int i=0;i<ftpFiles.length;i++)
{
if(ftpFiles[i].isDirectory())
iflag=true;
}
}
return iflag;
}
/**
* 删除指定文件
* @param pathName
* @return
* @throws IOException
*/
public boolean deleteFile(String pathName) throws Exception
{
return ftpClient.deleteFile(pathName);
}
/**
* 上传文件
* @param localFilePath 本地文件路径
* @param remoteFilePath FTP文件名称
* @param delFile 上传完成后是否删除本地文件
* @return
* @throws IOException
*/
public boolean uploadFile(String localFilePath, String remoteFilePath, boolean delFile) throws Exception
{
boolean flag = false;
InputStream iStream = null;
try
{
setFileType();
iStream = new FileInputStream(localFilePath);
flag = ftpClient.storeFile(remoteFilePath, iStream);
}
catch (IOException e)
{
// log.error("FTP上传文件失败",e);
flag = false;
return flag;
}
finally
{
if (iStream != null)
{
iStream.close();
}
//是否删除文件
if (delFile)
{
//FileUtils.forceDelete(new File(localFilePath));
}
}
return flag;
}
/**
* 上传文件
* @param localFilePath 本地文件路径
* @param remoteFilePath FTP文件名称
* @return
* @throws IOException
*/
public boolean uploadFile(String localFilePath, String remoteFilePath) throws Exception
{
return uploadFile(localFilePath, remoteFilePath, false);
}
/**
* 上传文件
* @param iStream 文件流
* @param remoteFilePath FTP文件名
* @return
* @throws IOException
*/
public boolean uploadFile(InputStream iStream, String remoteFilePath) throws Exception
{
boolean flag = false;
try
{
setFileType();
flag = ftpClient.storeFile(remoteFilePath, iStream);
}
catch (IOException e)
{
// log.error("FTP上传文件失败",e);
flag = false;
return flag;
}
finally
{
if (iStream != null)
{
iStream.close();
}
}
return flag;
}
/**
* 下载一个远程文件到本地的指定文件
* @param remoteFileName 远程文件名
* @param localFileName 本地文件名
* @param delFile 下载完成后是否删除远程文件
* @return
* @throws IOException
*/
public boolean downloadFile(String remoteFileName, String localFileName, boolean delFile) throws Exception
{
boolean flag = false;
File outfile = new File(localFileName);
OutputStream oStream = null;
try
{
oStream = new FileOutputStream(outfile);
// System.out.println("remoteFileName="+remoteFileName+" localFileName="+localFileName);
// outfile.setLastModified((long)20100422);
int icount=0;
while(!flag && icount<3)
{
try{
// System.out.println("连接...icount=["+icount+"]");
connect();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//
ftpClient.setControlEncoding("GBK");
// setFileType();
flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes("GBK"),"ISO-8859-1"), oStream);
}catch(Exception ex)
{
ftpClient.disconnect();
System.out.println("下载失败,重新链接...["+icount+"]");
ex.printStackTrace();
}
icount++;
}
if (delFile)
ftpClient.deleteFile(remoteFileName);
}
catch (Exception e)
{
//log.error("FTP下载文件失败",e);
//flag = false;
//return flag;
//throw e;
e.printStackTrace();
}
finally
{
if(oStream!=null)
oStream.close();
}
return flag;
}
/**
* 下载一个远程文件到本地的指定文件
* @param remoteFileName 远程文件名
* @param localFileName 本地文件名
* @return
* @throws IOException
*/
public boolean downloadFile(String remoteFileName, String localFileName) throws Exception
{
return downloadFile(remoteFileName, localFileName, false);
}
/**
* 下载远程文件
* @param remoteFileName
* @return
* @throws IOException
*/
public InputStream downloadFile(String remoteFileName) throws Exception
{
return ftpClient.retrieveFileStream(remoteFileName);
}
/**
* 设置文件传输类型 是否采用二进制传输 默认为False
* @param binaryTransfer
*/
public void setBinaryTransfer(boolean binaryTransfer)
{
this.binaryTransfer = binaryTransfer;
}
/**
* 设置文件传输类型
*/
private void setFileType() throws Exception
{
// 设置文件传输类型
if (binaryTransfer)
{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
}
else
{
ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
}
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean changePath(String path)
{
boolean iflag=true;
try{
toRoot(path);
String patharray[]=path.split("/");
for(int i=0;i<patharray.length;i++)
{
if(patharray[i]!=null && patharray[i].length()>0)
{
//connect();
iflag=ftpClient.changeWorkingDirectory(patharray[i]);
// System.out.println("文件跳转 iflag="+iflag+" patharray["+i+"]="+patharray[i]);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return iflag;
}
public boolean createPath(String path) //创建多层文件夹
{
boolean iflag=true;
try {
toRoot(path);
String patharray[] = path.split("/");
for (int i = 0; i < patharray.length; i++) {
if (patharray[i] != null && patharray[i].length() > 0) {
iflag = ftpClient.changeWorkingDirectory(patharray[i]);
if (!iflag) {
createDirectory(patharray[i]);
ftpClient.changeWorkingDirectory(patharray[i]);
}
// System.out.println("文件跳转 iflag=" + iflag + " patharray["+ i + "]=" + patharray[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return iflag;
}
public void toRoot(String path)
{
try{
int icount=0;
boolean iflag=false;
// connect();
iflag=ftpClient.changeWorkingDirectory("/");
// while(icount<3)
// {
// try{
// connect();
// iflag=ftpClient.changeWorkingDirectory("/");
// //iflag=true;
// }catch (Exception e)
// {
iflag=false;
// e.printStackTrace();
// }
//
// if(iflag)
// break;
// else{
// boolean ilogin=ftpClient.changeWorkingDirectory("/");
// if(ilogin)
// System.out.println("["+icount+"]重新读取根目录成功!");
// else
// System.out.println("["+icount+"]重新读取根目录失败!");
// }
// icount++;
// }
}catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
//String server, int port, String username, String password
FTPUtil ftp=new FTPUtil("127.0.0.1",221,"test","123456");
try{
ftp.connect();
ftp.binaryTransfer=true;
ftp.setBinaryTransfer(true);
ftp.ftpClient.setControlEncoding("GBK");
// System.out.println("~~~~~~~~~~~~~~~~~~~ files="+ftp.ftpClient.listFiles("/com/xwtech/cspf/webservice/ringservice").length);
boolean ichange=ftp.changeDirectory("com"); //ftp.changePath("com");
System.out.println("~~~~~~~~~~~~~~~~~~~ichange="+ichange+" files="+ftp.getFileList().size());
boolean iflag=ftp.downloadFile(new String("/TestClient.java".getBytes("GBK"),"ISO-8859-1"), "D:\\helloSMS\\TestClient.java", false);
System.out.println("~~~~~~~~~~~~~~~~~~~iflag="+iflag);
}catch(Exception e)
{
e.printStackTrace();
}
}
}