public void parseRequest(Socket socket) throws IOException { InputStream is = socket.getInputStream(); byte[] b = new byte[is.available()]; is.read(b); //is.close(); }
public void parseResponse(Socket socket) throws IOException { OutputStream os = socket.getOutputStream();
File file = new File("D:\\teste.jpg"); StringBuilder httpHead = new StringBuilder();
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpEngine {
private ServerSocket serverSocket;
public void start() throws IOException {
serverSocket = new ServerSocket(8080, 3);
while(true) {
Socket socket = serverSocket.accept();
parseRequest(socket);
parseResponse(socket);
socket.close();
}
}
public void parseRequest(Socket socket) throws IOException {
InputStream is = socket.getInputStream();
byte[] b = new byte[is.available()];
is.read(b);
//is.close();
}
public void parseResponse(Socket socket) throws IOException {
OutputStream os = socket.getOutputStream();
File file = new File("D:\\teste.jpg");
StringBuilder httpHead = new StringBuilder();
httpHead.append("HTTP/1.1 200 OK\r\n")
.append("Server: Microsoft-IIS/5.0\r\n")
.append("ContentType: application/x-download\r\n")
.append("Content-Disposition: attachment;filename=" + file.getName()+ "\r\n\r\n");
os.write(httpHead.toString().getBytes());
FileInputStream is = new FileInputStream(file);
byte[] b = new byte[1024];
while(is.read(b) != -1) {
os.write(b);
}
os.flush();
os.close();
}
public static void main(String args[]) throws Exception {
new HttpEngine().start();
}
}
在浏览器里面打http://localhost:8080,图片文件就下载下来了但是太复杂的文件:如pdf,download下来后有错误。因为我只用了非完整的http协议。lz自己完善下然后你在网页里面用<a href="http://localhost:8080">下载</a>,应该也是可以的