代码案例:package com.what21.http.core4_4;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.apache.http.ConnectionClosedException;
import org.apache.http.ExceptionLogger;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.bootstrap.HttpServer;
import org.apache.http.impl.bootstrap.ServerBootstrap;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
public class What21HttpFileServer {
public static void main(String[] args) {
// 本地操作系统服务目录
String docRoot = "D:\\Apps\\Java";
try {
final HttpServer server = ServerBootstrap.bootstrap()
.setListenerPort(10021)
.setServerInfo("What21/1.1")
.setExceptionLogger(new StdErrorExceptionLogger())
.registerHandler("*", new HttpFileHandler(docRoot))
.create();
// 启动服务
server.start();
server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
// 运行一段时间后停止服务
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
server.shutdown(5, TimeUnit.SECONDS);
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 标准异常处理
static class StdErrorExceptionLogger implements ExceptionLogger {
@Override
public void log(final Exception ex) {
if (ex instanceof SocketTimeoutException) {
System.err.println("连接超时.");
} else if (ex instanceof ConnectionClosedException) {
System.err.println(ex.getMessage());
} else {
ex.printStackTrace();
}
}
}
// 文件处理类
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
// 请求处理方法
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
// 请求方法
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " 不支持的请求方法");
}
// 请求的URI
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("传入实体内容 (字节数):" + entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
// 判断本地文件是否存在
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
// 返回信息
StringBuilder sb = new StringBuilder();
sb.append("
");
sb.append("File" + file.getPath() + "not found");
sb.append("");
StringEntity entity = new StringEntity(
sb.toString(),
ContentType.create("text/html", "UTF-8"));
response.setEntity(entity);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
// 返回信息
StringBuilder sb = new StringBuilder();
sb.append("
");
sb.append("访问拒绝");
sb.append("");
StringEntity entity = new StringEntity(
sb.toString(),
ContentType.create("text/html", "UTF-8"));
response.setEntity(entity);
System.out.println("不能够读取文件: " + file.getPath());
} else {
// 如果文件存在,就输出
HttpCoreContext coreContext = HttpCoreContext.adapt(context);
HttpConnection conn = coreContext.getConnection(HttpConnection.class);
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null));
response.setEntity(body);
System.out.println(conn + ": 传输文件 " + file.getPath());
}
}
}
}
实现功能:
1、通过浏览器访问地址:http://127.0.0.1:10021/look.txt,可以查看到本地计算机look.txt文件的内容。
2、通过地址:http://127.0.0.1:10021/,提交(POST)的数据,后台程序可以正确读取。