學習點sftp的訪問
學習點HttpURLConnection的使用
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public void parse(){
Session sshSession = null;
ChannelSftp sftp = null;
String beforeDat=getBeforeDate();
try {
// 串連sftp伺服器
JSch jsch = new JSch();
sshSession = jsch.getSession("ftp-music","192.1.1.1",50022);
sshSession.setPassword("WtLv53xHCwGRQN66dQ1C");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
//sftp.cd("MMLog");// 跳至檔案存放路徑
InputStream is=sftp.get("/MMLog/download_"+getBeforeDate()+".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
char[] ch=new char[1024];
while(br.read(ch)!=-1){
System.out.println(ch);
//HttpURLConnection con=new
}
sftp.disconnect();
sshSession.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sftp.isConnected()) {
try {
sftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 調用伺服器介面
*/
public void connectionClient(){
try {
URL url = new URL("http://127.0.0.1:8080/mmServer/plug-in/sub/orderProduct.aspx?contentid=1001010");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.addRequestProperty("gt", "isme");
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
connection.connect();
// 取得輸入資料流,並使用Reader讀取
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
System.out.println("=============================");
System.out.println("Contents of get request");
System.out.println("=============================");
String lines;
while ((lines = reader.readLine()) != null) {
System.out.println(lines);
}
reader.close();
// 中斷連線
connection.disconnect();
System.out.println("=============================");
System.out.println("Contents of get request ends");
System.out.println("=============================");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 擷取上一天的日期
*/
private String getBeforeDate()
{
//日誌日期,取前一天
Date current = new Date();
Calendar c = Calendar.getInstance();
c.setTime(current);
int date = c.get(Calendar.DATE);
c.set(Calendar.DATE, date -1);
String beforDateStr = new SimpleDateFormat("yyyyMMdd").format(c.getTime());
return beforDateStr;
}