阿帕奇服务器文件上传,Apache HttpCore4.4基于经典的IO实现HTTP文件传输服务器

代码案例: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)的数据,后台程序可以正确读取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值