简单的JAVA HTTP server 如何解析附件

想做一个简单的图片上传服务器,发现JDK6中有个HttpServer 可以支持简单的Server比用Socket简单多了,目前只是想获取Request中的附件.但是获取了全部的Request保存在文本中.但是如何解析请求中的附件确无从下手


/**
*
* @author rikugun
*/
public class Main {

public static void main(String[] args) {
try {
HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0);//设置HttpServer的端口为8888
hs.createContext("/pic", new PicHandler());//用PicHandler类内处理到/pic的请求
hs.setExecutor(null); // creates a default executor
hs.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}


PicHandler.java

/**
*
* @author rikugun
*/
public class PicHandler implements HttpHandler {

public void handle(HttpExchange t) throws IOException {

String response = "";
String mt = t.getRequestMethod();
if (t.getRequestMethod().equals("GET")) {
response = "<h3>请使用POST提交图片!</h3>";
} else {
InputStream is = t.getRequestBody();
doUpload(is);
response = "<h3>上传成功!</h3>";
}
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}

private void doUpload(InputStream is) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("out.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(PicHandler.class.getName()).log(Level.SEVERE, null, ex);
}
byte b[] = new byte[8192];
int isEnd = 0;
while (true) {
try {
isEnd = is.read(b);
if (isEnd == -1) {
//文件末尾
break;
}
System.out.println(b.toString());
fos.write(b);
} catch (IOException ex) {
ex.printStackTrace();
break;
}
}
try {
fos.close();
is.close();
} catch (IOException ex) {
Logger.getLogger(PicHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值