浏览器请求android HttpService显示图像

时间:2012-03-11 00:54:21

标签: android image browser webserver httpservice

我在android上创建了http服务。现在我正在尝试让HttpService向浏览器显示一些图像。我在浏览器中写了一个url(例如http://127.0.0.1:6789/home.html(我玩模拟器))。 http服务发送给我html如下:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> 
<title>File Upload</title> 
</head> 
<body> 
<td><img src='127.0.0.1:6789/1.png'/></td><br>
<td><img src='127.0.0.1:6789/2.png'/></td><br>
</body> 

服务器端的一些代码是:

/*some variables*/    
private static final String IMAGE_PATTERN = "/*.png";
/*some code*/
registry.register(IMAGE_PATTERN, new ImageCommandHandler(context)); 

ImageCommandHandler:

@Override
public void handle(HttpRequest request, HttpResponse response,
    HttpContext httpContext) throws HttpException, IOException {         
    final InputStream is = GetInpuStreamFromResource(getContext(), 
            R.drawable.back);

    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            int bufSize = 0;
            byte[] buf = new byte[32768];
            while(-1!=(bufSize=is.read(buf))){
                outstream.write(buf,0,bufSize);
            }
            outstream.flush();
            outstream.close();
            is.close();
        }
    });
    response.setHeader("Content-Type", "image/*");      
    response.setEntity(entity);

或其他方式

@Override
public void handle(HttpRequest request, HttpResponse response,
    HttpContext httpContext) throws HttpException, IOException {

    final File f= new File("/sdcard/Tulips.jpg");       
    String contentType = URLConnection.guessContentTypeFromName(f.getAbsolutePath());
    FileEntity entity = new FileEntity(f, contentType);     
    response.setHeader("Content-Type",  contentType);
    response.setEntity(entity);
}

我已经尝试过两种方式,但无论如何都没有任何图像!它出什么问题了?我如何使用JavaScript的文件? 感谢。

1 个答案:

答案 0 :(得分:0)

它完美无缺!我的错误是我写的:

<img src='127.0.0.1:6789/2.png'/>

但它返回空白页面,因为我错过了 http://

我应该写如下:

<img src='http://127.0.0.1:6789/2.png'/>

感谢。