2012-04-19 2 views
0

Я пытаюсь загрузить данные с локального сервера на своем эмуляторе, но я не получаю данные. Как эта задача может быть выполненаНевозможно загрузить файл с локального сервера на эмулятор android

моей загрузки активность

public class DownloadZipActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     UnzipManager.startUnzipping();//Downloader.getZipURL(); 
//  System.out.println(" file  "+file); 
    } 
} 

Моего Downloader.java является

public class Downloader { 

    public static String getZipURL(){ 
     String result = ""; 
     InputStream is = null; 
     try{ 
      String url = "http://www.example.com/webservice-demo/File name.zip"; 
      String thePath = URLEncoder.encode(url, "UTF-8"); 
      System.out.println("  thePath "+thePath); 
      HttpPost httppost = new HttpPost(thePath); 
      HttpParams httpParameters = new BasicHttpParams(); 

      int timeoutConnection = 3000; 
      HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 

      int timeoutSocket = 3000; 
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

      DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); 

      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
     }catch(Exception e){ 
      Log.e("getZipURL", "Error in http connection "+e.toString()); 
      return null; 
     } 

     try{ 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 

      result=sb.toString(); 
      return result; 
     }catch(Exception e){ 
      Log.e("convertZipURL", "Error converting result "+e.toString()); 
      return null; 
     } 
    }  


} 

И мой класс UnZipManager.java является

public class UnzipManager { 

     private static String BASE_FOLDER; 

     public static Context localContext; 
     /* 
     *You can use this flag to check whether Unzipping 
     *thread is still running.. 
     */ 
     public static boolean isDownloadInProgress; 
     /* 
     * After unzipping using this flag ,you can check 
     * whether any low memory exceptions 
     * Occurred or not..and alert user accordingly.. 
     */ 
     public static boolean isLowOnMemory; 

    public static void startUnzipping() 
     { 
      /* 
      * MAKE SURE THAT localContext VARIABLE HAS BEEN 
      * INITIALIZED BEFORE INVOKING THIS METHOD. 
      * 
      * ALSO MAKE SURE YOU HAVE SET "INTERNET" AND 
      * "NETWORK ACCESS STATE" PERMISSIONS IN 
      * APPLICATION'S MANIFEST FILE. 
      * 
      */ 
      Log.d("DEBUG","In startUnzipping()"); 
      //UnzipManager.BASE_FOLDER=UnzipManager.localContext.getFilesDir().getPath(); 
      /* 
      * 
      */ 
     // Log.d("DEBUG","BASE_FOLDER:"+UnzipManager.BASE_FOLDER); 
      UnzipManager.isLowOnMemory=false; 
      //Start unzipping in a thread..which is safer 
      //way to do high cost processes.. 
      new UnzipThread().start(); 
    } 

    private static class UnzipThread extends Thread{ 
      @Override 
      public void run() 
      { 
        UnzipManager.isDownloadInProgress=true; 
        Log.d("DEBUG","Unzipping----------------------------"); 
       URLConnection urlConnection ; 
       try 
       { 
         /************************************************ 
         * 
         * IF you are unzipping a zipped file save under 
         * some URL in remote server 
         * **********************************************/ 
        String url = "http://www.example.com/webservice-demo/Package name.zip"; 
        String thePath = URLEncoder.encode(url, "UTF-8"); 
        URL finalUrl =new URL(thePath 
          /* Url string where the zipped file is stored...*/); 
        urlConnection = finalUrl.openConnection(); 

        //Get the size of the (zipped file's) inputstream from server.. 
         int contentLength=urlConnection.getContentLength(); 
         Log.d("DEBUG", "urlConnection.getContentLength():"+contentLength); 
        /***************************************************** 
        * 
        * YOU CAN GET INPUT STREAM OF A ZIPPED FILE FROM 
        * ASSETS FOLDER AS WELL..,IN THAT CASE JUST PASS THAT 
        * INPUTSTEAM OVER HERE...MAKE SURE YOU 
        * HAVE SET STREAM CONTENT LENGTH OF THE SAME.. 
        * 
        ******************************************************/ 
        ZipInputStream zipInputStream = new ZipInputStream(urlConnection.getInputStream()); 
        /* 
         * Iterate over all the files and folders 
         */ 
        for (ZipEntry zipEntry = zipInputStream.getNextEntry(); 
          zipEntry != null; zipEntry = zipInputStream.getNextEntry()) 
          { 
           Log.d("DEBUG","Extracting: " + zipEntry.getName() + "..."); 

          /* 
           * Extracted file will be saved with same 
           * file name that in zipped folder. 
           */ 
           String innerFileName = BASE_FOLDER + File.separator + zipEntry.getName(); 
           File innerFile = new File(innerFileName); 
           /* 
            * Checking for pre-existence of the file and 
            * taking necessary actions 
            */ 
           if (innerFile.exists()) 
           { 
             Log.d("DEBUG","The Entry already exits!, so deleting.."); 
             innerFile.delete(); 
           } 

           /* 
           * Checking for extracted entry for folder 
           * type..and taking necessary actions 
           */ 
           if (zipEntry.isDirectory()) 
           { 
            Log.d("DEBUG","The Entry is a directory.."); 
            innerFile.mkdirs(); 
           } 
           else 
           { 
            Log.d("DEBUG","The Entry is a file.."); 
            FileOutputStream outputStream = new FileOutputStream(innerFileName); 
            final int BUFFER_SIZE = 2048; 

           /* 
           * Get the buffered output stream.. 
           * 
           */ 
           BufferedOutputStream bufferedOutputStream = 
            new BufferedOutputStream(outputStream,BUFFER_SIZE); 
             /* 
             * Write into the file's buffered output stream ,.. 
             */ 
             int count = 0; 
             byte[] buffer = new byte[BUFFER_SIZE]; 
             while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) 
             { 
               bufferedOutputStream.write(buffer, 0, count); 
             } 
             /*********************************************** 
             * IF YOU WANT TO TRACK NO OF FILES DOWNLOADED, 
             * HAVE A STATIC COUNTER VARIABLE, INITIALIZE IT 
             * IN startUnzipping() before calling startUnZipping(), 
             * AND INCREMENT THE COUNTER VARIABLE 
             * OVER HERE..LATER YOU CAN USE VALUE OF 
             * COUNTER VARIABLE TO CROSS VERIFY WHETHER ALL 
             * ZIPPED FILES PROPERLY UNZIPPED AND SAVED OR NOT. 
             * 
             * ************************************************ 
             */ 
             /* 
             * Handle closing of output streams.. 
             */ 
             bufferedOutputStream.flush(); 
             bufferedOutputStream.close(); 
            } 
           /* 
            * Finish the current zipEntry 
            */ 
           zipInputStream.closeEntry(); 
          } 
          /* 
          * Handle closing of input stream... 
          */ 
          zipInputStream.close(); 
          Log.d("DEBUG","--------------------------------"); 
          Log.d("DEBUG","Unzipping completed.."); 
        } 
        catch (IOException e) 
        { 
          Log.d("DEBUG","Exception occured: " + e.getMessage()); 
          if(e.getMessage().equalsIgnoreCase("No space left on device")) 
            { 
             UnzipManager.isLowOnMemory=true; 
          } 
          e.printStackTrace(); 
        } 
        UnzipManager.isDownloadInProgress=false; 
      } 
     }; 
} 
+0

Я не вижу, где вы указываете, в каком файле вы пишете загруженный контент ... ваш код выглядит как копирование и вставка много ... – WarrenFaith

+0

Сбой? Если это так. Если это не так, вы должны определить ту часть, где она не работает. – Cristian

+0

MalformedException: протокол не найден, я предоставил правильный URL – user1196969

ответ

0

вы должны добавить разрешение интернета в файле mainfest.xml

2

вы должны изменить URL на:

url = "http://localhost/example.com/webservice-demo/Package name.zip"; 

локального = 10.0.2.2 является локальным вашой emulater Я использую этот адрес, и я не specifie WWW, хотя мои папки находятся в WWW.

Смежные вопросы