t; + readByte);
bis.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Java技术体验:HTTP多线程下载,端口侦听和自启动服务(2)
时间:2011-02-04 csdn博客 赵学庆
二、做成Http的服务,侦听某个端口
使用了JDK6的特性,大家自己看代码吧,并不复杂
package net.java2000.tools;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
/**
* 下载程序的服务版本。<br>
* 可以供其它程序调用,而不是局限于java
*
* @author 赵学庆 www.java2000.net
*/
public class HTTPDownloadService {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
int port = 60080;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch (Exception ex) {}
}
// 绑定端口
InetSocketAddress addr = new InetSocketAddress(port);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/", new HTTPDownloaderServiceHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}
}
/**
* 下载的服务器
*
* @author 赵学庆 www.java2000.net
*/
class HTTPDownloaderServiceHandler implements HttpHandler {
private static Pattern p = Pattern.compile("\\?page=(.*?)\\&rpage=(.*?)&savepath=(.*)contentquot;);
public void handle(HttpExchange httpExchange) {
try {
Matcher m = p.matcher(httpExchange.getRequestURI().toString());
String response = "OK";
if (m.find()) {
try {
new HTTPDownloader(URLDecoder.decode(m.group(1), "GBK"), URLDecoder.decode(m.group(2), "GBK"), URLDecoder.decode(m.group(3), "GBK"), 10).start();
} catch (Exception e) {
response = "ERROR -1";
e.printStackTrace();
}
} else {
response = "ERROR 1";
}
httpExchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
httpExchange.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Java技术体验:HTTP多线程下载,端口侦听和自启动服务(3)
时间:2011-02-04 csdn博客 赵学庆
这个程序可以单独运行的,通过
http://127.0.0.1:60080
访问,参数是固定顺序的,比如
http://127.0.0.1:60080?page=http://www.csdn.net&rpage=http://blog.csdn.net&savepath=d:/csdn.html
三个参数分别代表了
page = 被下载的页面
rpage = referer的页面,用来 |