基于HTTP协议的文件传输,续!续!续!
上星期五问的问题已经解决了,现在的问题是,文件上传后,文件莫名其妙变大了(多了个http协议头)
现在的问题不用说也知道了。。。server端写文件时怎么忽略掉http协议头
源代码如下:
Server.java
public class Server {
public static void main(String[] args) {
try {
HttpServer hs = HttpServer.create(new InetSocketAddress("localhost",7070), 0);
hs.createContext("/", new MyHandler());
hs.setExecutor(null);
hs.start();
} catch (IOException e) {
e.printStackTrace();
}
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
FileOutputStream out = new FileOutputStream(new File("D:/l7.bin"));
byte[] b = new byte[1024];
int n = 0;
while ((n = is.read(b)) != -1) {
out.write(b, 0, n);
}
out.flush();
out.close();
}
}
}
Client.java
public class Client {
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
File f = new File("D:/l7-maxnet.bin");
int statusCode = -1;
PostMethod filePost = new PostMethod("http://127.0.0.1:7070");
Part[] parts = { new FilePart(f.getName(), f) };
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost
.getParams()));
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(1000*30);
try {
statusCode = client.executeMethod(filePost);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println(statusCode);
filePost.releaseConnection();
}
}
}