java IOException:使用HttpHandler破解管道来提供mp3。仅限Android浏览器

时间:2015-11-11 03:14:45

标签: java android mp3 httphandler

我正在尝试使用HttpHandler提供一个mp3并获得一个破损的管道。它适用于我的Mac和我的iPad上的谷歌浏览器,但Android导致HttpHander在获得IOException后挂起,我必须重新启动。使用非常简单的代码,可以正常使用图像和HTML。

       try {
            String requestURI = t.getRequestURI().toString().substring(1);

            if(requestURI.equals("") || requestURI.equals("/"))
                requestURI = "index.htm";

            requestURI = requestURI.replaceAll("%20", " ");

            if(requestURI.contains("mp3")) {
                urlToResource = new File(System.getProperty("user.home") + "/test/" +
                        requestURI).toURI().toURL();
            }

            System.out.println("Modified requestURI:" + requestURI);

            if(requestURI.contains("mp3")) {
                sContentType = "audio/mpeg";
            } else if(requestURI.contains("png")) {
                sContentType = "image/png";
            } else if(requestURI.contains("jpg")) {
                sContentType = "image/jpg";
            } else if(requestURI.contains("favicon.ico")) {
                sContentType = "content/unknown";
            } else if(requestURI.contains("css")) {
                sContentType = "text/css";
            } else {
                sContentType = "text/html";
            }

            if(!requestURI.contains("mp3")) {
                urlToResource = new File("src/com/daford/web/" + requestURI).toURI().toURL();
            }

            if(urlToResource != null) {
                conn = urlToResource.openConnection();
                int size = conn.getContentLength();

                System.out.println("file " + requestURI + " size is:" + size);

                inConnectionReader = conn.getInputStream();
                headers = t.getResponseHeaders();
                headers.add("Content-Type", sContentType);
                t.sendResponseHeaders(200, size);
                os = t.getResponseBody();
                int iReadByte = inConnectionReader.read();
                while (iReadByte != -1) {
                    os.write(iReadByte);
                    iReadByte = inConnectionReader.read();
                }
            } else {
                headers = t.getResponseHeaders();
                headers.add("Content-Type", "text/html");
                String sErrorMessage = "Error getting webpage.";
                t.sendResponseHeaders(404, sErrorMessage.length());
                os = t.getResponseBody();
                os.write(sErrorMessage.getBytes());
            }

            if(os != null) {
                os.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

0 个答案:

没有答案