经常用,先放这里,用的时候过来拿!
<%@page import="java.net.*,java.io.*"%>
<%!
public boolean saveurlas(string photourl, string filename) {
//此方法只能用户http协议
try {
url url = new url(photourl);
httpurlconnection connection = (httpurlconnection) url.openconnection();
datainputstream in = new datainputstream(connection.getinputstream());
dataoutputstream out = new dataoutputstream(new fileoutputstream(filename));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
return true;
}
catch (exception e) {
return false;
}
}
public string getdocumentat(string urlstring) {
//此方法兼容http和ftp协议
stringbuffer document = new stringbuffer();
try {
url url = new url(urlstring);
urlconnection conn = url.openconnection();
bufferedreader reader = new bufferedreader(new inputstreamreader(conn.
getinputstream()));
string line = null;
while ( (line = reader.readline()) != null) {
document.append(line + "/n");
}
reader.close();
}
catch (malformedurlexception e) {
system.out.println("unable to connect to url: " + urlstring);
}
catch (ioexception e) {
system.out.println("ioexception when connecting to url: " + urlstring);
}
return document.tostring();
}
%>
<%
//测试
string photourl = "http://www.alixixi.com/uploadpic/2007-7/200777112920214.jpg";
string filename = photourl.substring(photourl.lastindexof("/"));
string filepath = "d:/ghost/";
boolean flag = saveurlas(photourl, filepath + filename);
out.println("run ok!/n<br>get url file " + flag);
%>