我正在使用Android上的Web服务器而我无法将二进制文件发送到浏览器。提前致谢
如何将二进制数据发送到浏览器。请使用outputstream和inputstream来做。
Socket soc=server.accept();
BufferedReader buff=new BufferedReader(new InputStreamReader(soc.getInputStream()));
try{
String req=buff.readLine().replace(" HTTP/1.0","").replace(" HTTP/1.1","").replace("GET ","");
//setTitle(req);
//buff.close();
File f=new File(homedir+req);
if(f.isDirectory()){
File f2=new File(homedir+req+"/index.html");
File f3=new File(homedir+req+"/INDEX.html");
if(f2.exists()||f3.exists()){
try{
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
pw.print("HTTP/1.0 200 OK\n\rContent-type: text/html\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f2);
copyStream(inst,out);
out.close();
pw.close();
}catch(Exception k){
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
pw.print("HTTP/1.0 200 OK\n\rContent-type: text/html\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f3);
copyStream(inst,out);
inst.close();
out.close();
pw.close();
}
}else
throw new Exception("file not found");
}else{
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
String mim="";
try{
mim=MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.getName().substring(f.getName().lastIndexOf(".")+1));
}catch(Exception k){
mim="text/html";
}
if(mim.isEmpty()){
mim="text/html";
}
pw.print("HTTP/1.0 200 OK\n\rContent-type: "+mim+"\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f);
copyStream(inst,out);
inst.close();
out.close();
pw.close();
}
}catch(Exception k){
PrintWriter pw=new PrintWriter(soc.getOutputStream());
pw.print("<html><h1>"+k.getMessage()+"</h1></html>");
pw.flush();
pw.close();
}
buff.close();
soc.close();
调用此选项时,浏览器显示以下内容:
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
String mim="";
try{
mim=MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.getName().substring(f.getName().lastIndexOf(".")+1));
}catch(Exception k){
mim="text/html";
}
if(mim.isEmpty()){
mim="text/html";
}
pw.print("HTTP/1.0 200 OK\n\rContent-type: "+mim+"\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f);
copyStream(inst,out);
inst.close();
out.close();
pw.close();
以下是浏览器显示的内容:
答案 0 :(得分:0)
在此处更改:
String mim="image/"
try{
mim += MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.getName().substring(f.getName().lastIndexOf(".")+1));
此代码为图片设置了正确的内容类型,如:
image/jpg
image/jpeg
image/png