2012-07-06 75 views
1

我想通过http获取音频文件从安全的宁静服务获取,我已经成功地接收和解析文本XML服务,但有点困惑,如何处理音频文件。如何通过HTTP获取音频文件?

代码调用安全RESTful服务和XML响应

String callWebService(String serviceURL) { 
     // http get client 
     HttpClient client = getClient(); 
     HttpGet getRequest = new HttpGet(); 

     try { 
      // construct a URI object 
      getRequest.setURI(new URI(serviceURL)); 
     } catch (URISyntaxException e) { 
      Log.e("URISyntaxException", e.toString()); 
     } 

     // buffer reader to read the response 
     BufferedReader in = null; 
     // the service response 
     HttpResponse response = null; 
     try { 
      // execute the request 
      response = client.execute(getRequest); 
     } catch (ClientProtocolException e) { 
      Log.e("ClientProtocolException", e.toString()); 
     } catch (IOException e) { 
      Log.e("IO exception", e.toString()); 
     } 
     try { 
      in = new BufferedReader(new InputStreamReader(response.getEntity() 
        .getContent())); 
     } catch (IllegalStateException e) { 
      Log.e("IllegalStateException", e.toString()); 
     } catch (IOException e) { 
      Log.e("IO exception", e.toString()); 
     } 
     StringBuffer buff = new StringBuffer(""); 
     String line = ""; 
     try { 
      while ((line = in.readLine()) != null) { 
       buff.append(line); 
      } 
     } catch (IOException e) { 
      Log.e("IO exception", e.toString()); 
      return e.getMessage(); 
     } 

     try { 
      in.close(); 
     } catch (IOException e) { 
      Log.e("IO exception", e.toString()); 
     } 
     // response, need to be parsed 
     return buff.toString(); 
    } 

回答

0

可能这一个帮助你..

public static void downloadFile(String fileURL, String fileName) { 
    try { 
     // fileURL=fileURL.replaceAll("amp;", ""); 
     Log.e(fileURL, fileName); 
     String RootDir = Environment.getExternalStorageDirectory() 
       .toString(); 

     File RootFile = new File(RootDir); 
     new File(RootDir + Commons.dataPath).mkdirs(); 
     File file = new File(RootFile + Commons.dataPath + fileName); 
     if (file.exists()) { 

      file.delete(); 
     } 
     file.createNewFile(); 

     URL u = new URL(fileURL); 
     HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
     c.setRequestMethod("GET"); 
     c.setDoOutput(true); 
     c.connect(); 
     FileOutputStream f = new FileOutputStream(new File(
       "mnt/sdcard"+Commons.dataPath + fileName)); 
     InputStream in = c.getInputStream(); 
     byte[] buffer = new byte[1024]; 
     int len1 = 0; 

     while ((len1 = in.read(buffer)) > 0) { 
      f.write(buffer, 0, len1); 
     } 
     f.close(); 

    } catch (Exception e) { 

     e.printStackTrace(); 
    } 

}