上星期五问的问题已经解决了,现在的问题是,文件上传后,文件莫名其妙变大了(多了个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();
}
}
}

解决方案 »

  1.   

    当然有个很笨的方法:类似的判断是否是协议头。不过我想应该有更好的解决办法吧
    甚至用到commons.fileupload
      

  2.   

    对HTTP协议要有了解
    很容易解决
    正文和头之间有个空行
    这个空行代表头的结束
      

  3.   

    对于http协议文件上传会有头其实很正常,因为是需要区分多文件以及表单其它元素的提交内容。
    因为无论你上传多少个文件,多少个表单元素数据,都是放在一个流中的,如果你把这个流直接保存在一个文件中是不行的,所以你必须实现对这个流的解析。现在网络上已经有已经实现的对流解析的现成的实现,例如fileupload.jar,你可以去搜索一下。
      

  4.   

    我在尝试用fileupload.jar不过貌似只能解析request