Skip to content

Instantly share code, notes, and snippets.

@st63jun
Created February 14, 2012 12:47
Show Gist options
  • Save st63jun/1826605 to your computer and use it in GitHub Desktop.
Save st63jun/1826605 to your computer and use it in GitHub Desktop.
ファイルをダウンロードさせるだけのHttpd
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpContext;
public class Httpd {
public static class FileDownloadHandler implements HttpHandler {
private File basedir;
public FileDownloadHandler(File basedir) throws IOException {
if (!basedir.isDirectory()) {
throw new IOException(basedir.getPath() + " is not directory");
}
this.basedir = basedir;
}
public void handle(HttpExchange exchange) {
String context = exchange.getHttpContext().getPath();
String request = exchange.getRequestURI().getPath();
String path = request.substring(context.length(), request.length());
try {
File file = new File(basedir, path);
if (file.isFile() && file.canRead()) {
exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
exchange.sendResponseHeaders(200, file.length());
OutputStream os = exchange.getResponseBody();
InputStream is = new FileInputStream(file);
int b;
while ((b = is.read()) != -1) {
os.write(b);
}
os.close();
is.close();
}
else {
String message = new StringBuilder()
.append("<h1>404 Not Found</h1>")
.append(exchange.getRequestURI() + " - そんなファイルない.")
.toString();
exchange.getResponseHeaders().add("Content-Type", "text/html");
exchange.sendResponseHeaders(404, message.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(message.getBytes());
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer server = HttpServer.create(addr, 0);
System.err.println("[HTTPD] Started on " + addr);
server.createContext("/", new FileDownloadHandler(new File("/tmp/hoge")));
server.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment